Java-- What is the class, how to define classes

What is the class

Class is an abstract concept, can not be directly used to use the properties and functions of the class, you must instantiate the class, we can use the keyword new (Static Static does not require modification to achieve new). In fact when we create an object, in addition to using the new keyword addition, the aid had to be done constructor to instantiate the class.

note
  1. The method of the same name generally class name, return type is not, no void (key parameter sub-void return type is free)
  2. At the time when the class definition must define its no-argument constructor, because no-argument constructor we actually call some method calls all the time.
    Examples of how to define a simple class.
class demo {
    String name; //名字
    int age;    //年龄

    public demo() {
    }   
                //无参数构造
    public demo(String name, int age) {
        this.name = name;
        this.age = age;
    }
                //有参数构造
}
The privatization of the class parameters defined class

After doing qualifiers private class will be modified before the parameter set and get methods, this model increases the security of the code. But more get and set methods.

class demo {
    private String name; //名字
    private int age;    //年龄

    public demo() {
    }
                //无参数构造
    public demo(String name, int age) {
        this.name = name;
        this.age = age;
    }
                //有参数构造

    public String getName() {
        return name;
    }           
                //get获取名字
    public void setName(String name) {
        this.name = name;
    }
                //set修改名字
    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
Published 15 original articles · won praise 8 · views 10000 +

Guess you like

Origin blog.csdn.net/Junzizhiai/article/details/102556359