Class and object, static decoration, this keyword, constructor

Keywords: Attribute Java

Three characteristics of object-oriented: encapsulation, inheritance and polymorphism

Class definition

Class is actually a custom type. Like int and char, it can be used to define variables. Variables of this type are collectively referred to as reference variables. That is, all classes are reference types.
Class is the abstraction of a batch of objects, which can be understood as a concept: an object is a concrete entity.
Object oriented is a way to describe the objective world with code (class). A class mainly contains the attributes and behaviors of a thing
The process of creating objects with class types is called class instantiation

  1. A class is just a model thing. It defines the members of a class. A class does not allocate the actual memory space to store it.
  2. A class can instantiate multiple objects. The instantiated objects occupy the actual physical space and store class member variables.
    Define the syntax of the class:
[modifier] class name{
	0 -- multiple constructor definitions;
	0 -- multiple member variables;
	0 -- multiple methods;
}

Members in a class can call each other, but members decorated with static cannot call members not decorated with static

Member variable (field)

class Person {
    public String name;   // field
    public int age; }
class Test {
    public static void main(String[] args) {
        Person person = new Person();
        System.out.println(person.name);
        System.out.println(person.age);
   }
}

The name and age in the above code are the member variables of the Person class.
To access member variables in a class, you need to click '.'
However, note that if the member variable is a reference type and has no initial value assigned, the default value is null when accessing. If you want to get the length, you can't use. Length, because null.length is an exception.
method
Method is used to describe the behavior of an object. It is the same as the common method definition.
There is also a special method called construction method.
When instantiating an object, the method will be called automatically. The method name is the same as the class name, which is used for object initialization.

Static

1. Decoration attribute
2. Modification method
a) modify attributes. Java static attributes are related to classes and are independent of specific instances. In other words, different instances of the same class share the same static attribute.
b) modification method
If you apply the static keyword to any method, this method is called a static method.
Static methods belong to classes, not objects of classes.
Static methods can be called directly without creating an instance of the class.
Static methods can access static data members and change their values
A static decorated member indicates that it belongs to the class itself, not to a single instance of the class
Ordinary methods and member variables without static decoration belong to a single instance of this class, not to this class
In fact, the real function of static is to distinguish member variables, methods, internal classes and initialization block members. Static is a flag. Members with static decoration belong to the class itself, and members without static decoration belong to the instance of the class.
-------------------
Static methods cannot directly use non static data members or call non static methods (both are instance dependent).
All in all: static decorated methods and member variables can be called either by class or by instance (but there will be a warning when calling by instance); ordinary methods and member variables without static decoration can only be called by instance

class Person { 
 public int age;//Instance variables are stored in objects
 public String name;//Instance variables
 public String sex;//Instance variables
 public static int count;//Class variables are also called static variables. They have been generated at compile time. They belong to the class itself and only have one copy. Store in method area
 public final int SIZE = 10;//What is decorated by final is called a constant, which also belongs to an object. Decorated by final, cannot be changed later
 public static final int COUNT = 99;//Static constants belong to the class itself. Only one of them is modified by final and cannot be changed later.
 //Instance member function
 public void eat() { 
 int a = 10;//local variable
 System.out.println("eat()!"); 
 } 
 //Instance member function
 public void sleep() { 
 System.out.println("sleep()!"); 
 } 
 //Static member function
 public static void staticTest(){ 
 //Cannot access non static member
 //sex = "man"; error 
 System.out.println("StaticTest()"); 
 } 
} 
public class Main{ 
 public static void main(String[] args) { 
 //Generate object instanced object
 Person person = new Person();//person is a reference to an object
 System.out.println(person.age);//The default value is 0 
 System.out.println(person.name);//The default value is null 
 //System.out.println(person.count); / / there will be a warning! 
 //Correct access:
 System.out.println(Person.count); 
 System.out.println(Person.COUNT); 
 Person.staticTest(); 
 //Summary: all methods or properties decorated by static are independent of objects.
 person.eat(); 
 person.sleep(); 
 } 
}

Private implementation encapsulation

The two keywords private/ public represent "access control".
Member variables or member methods decorated by public can be directly used by class callers.
The member variable or member method decorated by private cannot be used by the class caller.
In fact, a property refers to a set of get() and set() methods

class Person { 
	 private String name;//Instance member variable
	 private int age; 
	 public void setName(String name){ 
	 //name = name; / / can't write like this
	 this.name = name;//this reference, representing the object calling the method
 } 
 public String getName(){ 
	 return name; 
 } 
 public void show(){ 
	 System.out.println("name: "+name+" age: "+age); 
 } 
} 
public static void main(String[] args) { 
	 Person person = new Person(); 
	 person.setName("caocao"); 
	 String name = person.getName(); 
	 System.out.println(name); 
	 person.show(); 
}

getName is the get() method, which means to get the value of this member.
setName is the set() method, which means to set the value of this member. When the parameter name of the set method is the same as the name of the member property in the class, if this is not used, it is equivalent to self assignment. This represents the current instance.
Citation.
Not all fields must be provided with set/ get methods, but which method should be determined according to the actual situation. In IDEA, alt + insert (or alt + F12) can be used to quickly generate set/ get methods. In VSCode, right-click menu - > source code operation can be used to automatically generate set/ get methods.

Construction method

The constructor is a special method, which is called automatically when a new object is instantiated with the keyword new, to complete the initialization operation
new execution process

  • Allocate memory space for objects
  • Construction method of calling object

Rule of grammar
1. Method name must be the same as class name
2. The constructor has no return value type declaration

There must be at least one construction method in each class (without clear definition, the system will generate a nonparametric construction)
If no constructor is provided in the class, the compiler will generate a constructor without parameters by default
If a constructor is defined in a class, the default nonparametric construct is no longer generated.
The construction method supports overloading. The overloading of rules and common methods is consistent
When an instance is generated, that is, when the new keyword is used to call the constructor, the constructor begins to execute, the constructor returns the instance of the class, and the return of the constructor is implicit

class Person { 
	 private String name;//Instance member variable
	 private int age; 
	 private String sex; 
	 //Default constructor construction object
	 public Person() { 
		 this.name = "caocao"; 
		 this.age = 10; 
		 this.sex = "male"; 
 } 
 //Constructor with 3 arguments
 public Person(String name,int age,String sex) { 
	 this.name = name; 
	 this.age = age; 
	 this.sex = sex; 
 } 
 public void show(){ 
	 System.out.println("name: "+name+" age: "+age+" sex: "+sex); 
 } 
} 
public class Main{ 
	 public static void main(String[] args) { 
		 Person p1 = new Person();//Call the constructor without parameters if the program does not provide one
		 p1.show(); 
		 Person p2 = new Person("zhangfei",80,"male");//Call constructor with 3 parameters
		 p2.show(); 
	 } 
}

this keyword

This indicates the current object reference (note that it is not the current object). You can use this to access the fields and methods of the object.

public class Person{
    public Person(){    //Constructor without parameters
        this("caocao");    //When an instance of new in main has no parameters, the constructor without parameters will be called. Then / / within this function, the constructor with one parameter will be called and can only be placed in the first line.
    }
    public Person(String name){    //Constructor with one parameter
        this.name=name;
    }
    public Person(String name,int age){    //Constructor with two arguments
        this.name=name;
        this.age=age;
    }
}

We will find that within the constructor, we can use this keyword. The constructor is used to construct objects. Before the objects are constructed, we use this. Does this represent the current object? Of course not. This represents a reference to the current object.
this keyword always points to the object that called the method
This can represent any object. When this appears in a method, the object it represents is uncertain, but its type is determined: it represents only the instance of the current class; when this method is called, the object it represents is determined, and who is calling this method will point to
This reference cannot be used in static decorated methods. Because static decorated methods do not depend on instances, they only belong to this class. This must point to an instance, so using this in static will cause the situation that you do not know who this points to
If you really want to use this in static decorated methods, you need to create a specific object.

Posted by NCllns on Thu, 24 Oct 2019 03:23:26 -0700