Object-oriented---classes and objects

The difference between process-oriented and object-oriented

Process-oriented, pay attention to the process, and write the code details yourself.
Object-oriented pays attention to the object. When writing code, refer to the methods of the existing classes in the jdk to realize the function, instead of writing it yourself.

The relationship between class and object

What is a class?

A class is a collection of related attributes and behaviors . It is a description of a class of things and is abstract.
Attributes : what (take the puppy as an example, color, breed, age, name)
corresponds to the Java class, attributes are member variables

String name;//名字
int age;//年龄

Behavior : What to do (take the puppy as an example, eat, sleep, play)
corresponds to the Java class, the behavior is the member method
(note: the member method does not write the static keyword!!!)

public void eat(){
    
    }//吃
public void sleep() {
    
    }//睡

What is an object?

Objects are instances of a class of things and are concrete.

The class is the template of the object, and the object is the entity of the class.
The analogy can be compared to a mobile phone design drawing, and the object can be compared to a real mobile phone.
To achieve functionality, we must instantiate a specific object based on the class, that is, create an object.

Creation and use of objects

1.
Import package import package name. Class name;
and the current class in the same package, you can not import the package
2. Create
format:
class name object name = new class name ();
3.
Use the member variable: object name. Member variables
Use member methods: object name. Member method (parameters)
(if you want to use it, use the object name. Who)

Example exercise-define a class to simulate "mobile phone" things

public class Phone {
    
    

    // 成员变量
    String brand; // 品牌
    double price; // 价格
    String color; // 颜色

    // 成员方法
    public void call(String who) {
    
    
        System.out.println("给" + who + "打电话");
    }

    public void sendMessage() {
    
    
        System.out.println("群发短信");
    }
}
public class Demo01PhoneOne {
    
    

    public static void main(String[] args) {
    
    
        // 根据Phone类,创建一个名为one的对象
        // 格式:类名称 对象名 = new 类名称();
        Phone one = new Phone();
      
        one.brand = "苹果";
        one.price = 8388.0;
        one.color = "黑色";
        System.out.println(one.brand); // 苹果
        System.out.println(one.price); // 8388.0
        System.out.println(one.color); // 黑色
        System.out.println("=========");

        one.call("乔布斯"); // 给乔布斯打电话
        one.sendMessage(); // 群发短信
    }

}

Memory graph of one object

Insert picture description here

Use object type as method parameter

When an object is passed as a parameter to a method, it actually passes the address value.

public class Demo04PhoneParam {
    
    

    public static void main(String[] args) {
    
    
        Phone one = new Phone();
        one.brand = "苹果";
        one.price = 5999.0;
        one.color = "玫瑰金";

        method(one); // 传递进去的参数其实就是地址值
    }

    public static void method(Phone param) {
    
    
        System.out.println(param.brand); // 苹果
        System.out.println(param.price); // 5999.0
        System.out.println(param.color); // 玫瑰金
    }

}

Use the object type as the return value of the method

public class Demo05PhoneReturn {
    
    

    public static void main(String[] args) {
    
    
        Phone two = getPhone();
        System.out.println(two.brand); // 苹果
        System.out.println(two.price); // 5999.0
        System.out.println(two.color); // 玫瑰金
    }

    public static Phone getPhone() {
    
    
        Phone one = new Phone();
        one.brand = "苹果";
        one.price = 5999.0;
        one.color = "玫瑰金";
        return one;
    }

}

Local variables and member variables

1. The location of the definition is different.
Local variables: inside the method.
Member variables: outside the method, directly written in the class

2. The scope of action is different.
Local variables: can only be used in methods, and can no longer be used when the methods are out.
Member variables: the entire class can be used in general.

3. The default values ​​are different.
Local variables: there is no default value. If you want to use it, you must manually assign a value.
Member variables: if you don’t have a value, there will be a default value. The rules are the same as arrays.

4. The location of the memory is different.
Local variables: located in the stack memory
Member variables: located in the heap memory

5. The life cycle is different.
Local variables: born as methods
are pushed onto the stack, and disappear as methods are popped off the stack. Member variables: born as objects are created, and disappear as objects are garbage collected

public class Demo01VariableDifference {
    
    

    String name; // 成员变量

    public void methodA() {
    
    
        int num = 20; // 局部变量
        System.out.println(num);
        System.out.println(name);
    }

    public void methodB(int param) {
    
     // 方法的参数就是局部变量
        // 参数在方法调用的时候,必然会被赋值的。
        System.out.println(param);

        int age; // 局部变量
//        System.out.println(age); // 没赋值不能用

//        System.out.println(num); // 错误写法!
        System.out.println(name);
    }

}

The encapsulation of the three characteristics of object-oriented

The manifestation of encapsulation in Java:

  1. Method is a kind of encapsulation
  2. The keyword private is also a kind of encapsulation
  3. Encapsulation is to hide some detailed information, invisible to the outside world, easy to modify, and enhance the maintainability of the code.
  4. Encapsulation can restrict users from unreasonable manipulation of attributes.

Case: When defining the age of Person, it is impossible to prevent an unreasonable value from being set in.
Solution: Use the private keyword to modify the member variables that need to be protected.

Once private is used for modification, then this class can still be accessed at will.
However, it cannot be accessed directly outside the scope of this category!

Therefore, define a pair of Getter/Setter methods to indirectly access private member variables.

Must be setXxx or getXxx naming rules.
(Note: For the boolean value in the basic type, the Getter method must be written in the form of isXxx, and the setXxx rule remains unchanged.)

  • 例如:public boolean isMale() {
    return male;
    }

For Getter, there can be no parameters, and the return value type corresponds to the member variable;
for Setter, there can be no return value, and the parameter type corresponds to the member variable.

public class Person {
    
    

    String name; // 姓名
    private int age; // 年龄

    public void show() {
    
    
        System.out.println("我叫:" + name + ",年龄:" + age);
    }

    // 这个成员方法,专门用于向age设置数据
    public void setAge(int num) {
    
    
        if (num < 100 && num >= 9) {
    
     // 如果是合理情况
            age = num;
        } else {
    
    
            System.out.println("数据不合理!");
        }
    }

    // 这个成员方法,专门用于获取age的数据
    public int getAge() {
    
    
        return age;
    }

}

public class Demo03Person {
    
    

    public static void main(String[] args) {
    
    
        Person person = new Person();
        person.show();

        person.name = "小明";
        person.setAge(20);
        person.show();
    }

}

The role of this keyword

When the local variable of the method and the member variable of the class have the same name, the local variable is preferred according to the "principle of proximity".
If you need to access the member variables in this class, you need to use the format:
this. member variable name

"By whom the method is called, whoever is this."

public class Person {
    
    

    String name; // 我自己的名字

    // 参数name是对方的名字
    // 成员变量name是自己的名字
    public void sayHello(String name) {
    
    
        System.out.println(name + ",你好。我是" + this.name);
        //System.out.println(this);
    }

}
public class Demo01Person {
    
    

    public static void main(String[] args) {
    
    
        Person person = new Person();
        // 设置我自己的名字
        person.name = "老哈";
        person.sayHello("小哈");

       // System.out.println(person); // 地址值
    }

}

Insert picture description here

Construction method

The construction method is a method specifically used to create an object. When we create an object through the keyword new, we are actually calling the construction method.
Format:
public class name (parameter type parameter name) { method body }

Precautions:

  1. The name of the constructor must be exactly the same as the name of the class, and the case must be the same
  2. Do not write the return value type in the constructor, and do not even write void
  3. The constructor cannot return a specific return value
  4. If no construction method is written, then the compiler will have a default construction method, without parameters, the method body does nothing.
public class Student {
public Student() {}
}
  1. Once you have written at least one constructor, the compiler will no longer have a default constructor.
  2. The construction method can also be overloaded.
    (Overload: the method name is the same, but the parameter list is different.)
public class Student {
    
    

    // 成员变量
    private String name;
    private int age;

    // 无参数的构造方法
    public Student() {
    
    
        System.out.println("无参构造方法执行啦!");
    }

    // 全参数的构造方法
    public Student(String name, int age) {
    
    
        System.out.println("全参构造方法执行啦!");
        this.name = name;
        this.age = age;
    }

    // Getter Setter
    public void setName(String name) {
    
    
        this.name = name;
    }

    public String getName() {
    
    
        return name;
    }

    public void setAge(int age) {
    
    
        this.age = age;
    }

    public int getAge() {
    
    
        return age;
    }

}
public class Demo02Student {
    
    

    public static void main(String[] args) {
    
    
        Student stu1 = new Student(); // 无参构造
        System.out.println("============");

        Student stu2 = new Student("小哈", 20); // 全参构造
        System.out.println("姓名:" + stu2.getName() + ",年龄:" + stu2.getAge());
        // 如果需要改变对象当中的成员变量数据内容,仍然还需要使用setXxx方法
        stu2.setAge(21); // 改变年龄
        System.out.println("姓名:" + stu2.getName() + ",年龄:" + stu2.getAge());

    }

}

Insert picture description here

Define a standard class

A standard class usually has the following four components:

  1. All member variables must be modified with the private keyword
  2. Write a pair of Getter/Setter methods for each member variable
  3. Write a parameterless construction method
  4. Write a full-parameter construction method

Such a standard class is also called Java Bean

ublic class Student {
    
    

    private String name; // 姓名
    private int age; // 年龄
    //定义完成员变量之后,光标放在下面的空白层,按住Alt+Insert键,选择"Getter和Setter" 就会自动生成Getter和Setter方法


    public Student() {
    
    
    }

    public Student(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public int getAge() {
    
    
        return age;
    }

    public void setAge(int age) {
    
    
        this.age = age;
    }
}

When writing code, after defining the member variables, place the cursor on the blank layer below, hold down Alt+Insert to
select "Getter and Setter", hold down Shift to select all and click ok, the Getter and Setter methods will be automatically generated.
Select "Constructor" and click Select None to automatically generate a method with no parameters; hold down Shift to select all and click ok to automatically generate a method with full parameters

Insert picture description here

Insert picture description here
Insert picture description here
Alt+Insert key (usually to the left of the Delete key), you can also find code-Generate in the menu bar
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_51492999/article/details/114946335