Java entry class, encapsulation, inheritance

Posted by bing_crosby on Sun, 02 Jan 2022 05:03:05 +0100

Class:

What are class members

Member methods and member variables decorated with static are called class members
Member variables decorated with static are called class variables
Member methods decorated with static are called class methods

What are instance variables
Member methods and member variables that are not decorated with static are called instance members
Member variables that are not decorated with static are called instance variables
Member methods that do not use static modification are called instance methods
For example:

public String name;  //This is the instance member (property) 
public static int age;//This is the class member (property) 

public void a(){
	System.out.println("My name is:"+this.name)
}                                    //This method without static is the instance method

public static void a(){           	//The static method is a class method
	System.out.println("My name is:"+this.name)
}

What is the difference between instance variables and class variables?

  1. All objects of this class share the same class variable, but each object has its own unique instance variable
  2. All objects of this class can change the value of class variables, but each object can only change its own instance variable value
  3. An object must be created before using the instance variable according to the object name Variable names are used, but class variables do not need to create objects
//Define a class
public class stu {
    public String name;  //This class has a name and this attribute belongs to an instance member, that is, it can be used only after instantiating an object
    //Define construction method
    public stu(){}    //In any case, define a parameterless construct
    public stu(String name){    //To define a parameter structure, you need to pass in a string name
       this.name = name;         //If this keyword is not used here, it will not match the above instance attribute
    }
    //Definition method
    public void a(){
        System.out.println(this.name);
    }
}

Use this class:

public class stu_Test {
    public static void main(String[] args) {
        //Instantiate two objects, based on the stu class
        stu s1 = new stu("Xiao Hong");   
        stu s2 = new stu("Xiao Wang");
        //Use the methods in the stu class
        s1.a();
        s2.a();
    }
    
    //stu s1 = new stu("little red"); Little red will be output
    //stu s2 = new stu("Xiao Wang"); Will output Xiao Wang
}
//Through this, we can understand that each object has its own instance variables (properties)

What is the difference between class methods and instance methods?

  1. . All such objects share class methods and instance methods
  2. Class methods use class names The method name ([parameter]) can be called without instantiating the object
  3. Instance methods use object names Method name ([parameter]) call

static keyword
Java classes provide two types of variables: static variables modified with static keyword and instance variables not modified with static keyword.
A static variable belongs to a class. There is only one copy in memory. As long as the class where the static variable is located is loaded, the static variable will be allocated space, so it can be used. There are two ways to reference static variables, namely "class. Static variable" and "object. Static variable"

static member method:

  1. Static methods are class methods that can be called without creating objects. Non static methods are object methods that can be used only after objects are created
  2. This and super keywords cannot be used in static methods, non static methods cannot be called, and only static member variables and member methods of the class can be accessed, because when static methods are called, the object of this class may not have been created, and even if they have been created, it is impossible to determine which object's method to call.

Use of static:

  1. Decorated member variable
  2. Modify member method
  3. Static code block
  4. Modifier class [can only modify internal classes, that is, static internal classes]
  5. Static guide package

static precautions:
Static can only access static, and non static can access both non static and static.

Encapsulation:

  • Concept of encapsulation
    Encapsulating objective things into abstract classes, and classes can only allow trusted classes or objects to operate their properties and methods, and hide untrusted classes or objects. This process is called encapsulation.
    In short: close your information and only show and use it to people you trust

-Classification of packages

  • Encapsulation of attributes: set the attributes to private (private) and restrict them to be used only inside the class

  • Encapsulation of methods: for encapsulation of methods, set the externally accessible methods to public and the externally inaccessible methods to private

-Use of encapsulation
Before encapsulating, let's learn a new modifier: private
Private: restrict its use only inside the class (that is, the methods and attributes modified by private can only be found and used inside the class. Outside the class, the attribute cannot be found, which also achieves the effect of encapsulation)

//Encapsulate the name attribute

private Strint name; //That is, we can't find the existence of this attribute outside the class

Now that the package is encapsulated, there must be methods to modify and use the package. Yes, this is the get/set method

get/set method

public class stu {
    private String name; 
    public void setName(String name){    //set method: this method is called by the object to modify private properties
        this.name = name;   
    }
    public String getName(){         //get method: this method can be used when the object calls this method
        return name;
    }
}

use:

public class stu_Test {
    public static void main(String[] args) {
    stu s =new stu();
    s.setName("Xiao Hong");  //Change the value of the private property name to little red
        System.out.println(s.getName());
   
}  //After the program runs, the output value is little red

Inheritance:

  • What is inheritance
    1: A new class can be derived from an existing class. This process is called inheritance
    2: In the process of inheritance, the new class is called a subclass, and the existing class is called a parent class. The subclass will inherit the properties and behavior of the parent class.

Inheritance syntax:

public class stu extends Student{   //Add extensions after the class name and write the inherited parent class
//Here, you can write properties and methods that are not issued by the parent class
	public String ID;  //Wait, wait

}

Note: inheritance cannot inherit the private properties and methods of the parent class!!! As long as it is decorated by private, it will not be inherited!!!

About subclasses:
In addition to having non private properties and methods of the parent class, a subclass can also extend its own properties and methods

Use of inheritance:

  1. Inheritance is single inheritance, that is, a class can only have one parent class.
  2. If a class does not explicitly inherit a class, it has a default parent class of Java Lang.Object class
  3. Inherits non private member variables and member methods of the parent class, but please note that subclasses cannot inherit the constructor of the parent class

In short: a subclass can inherit only one parent class. If this class does not inherit other classes, it inherits the Object class by default (Java comes with it)
Cannot inherit the constructor of the parent class.

Method override:
@overriding
What is method rewriting?:

  • The subclass is rewritten according to the method inherited from the parent class (the method name is the same)
  • Rewriting is a way to retain the father's method by using the super method (super will be discussed later)
    Note: constructor cannot be overridden

Rule for method override:

  1. Same method name, same parameter list (quantity, order, data type)
  2. If there is a return value, the return value is the same or its subclass, and the access permission cannot be stricter than that of the parent class
  3. A static method of a parent class cannot be overridden as a non static method. Conversely, a non static method of a parent class cannot be overridden as a static method
  4. A subclass can define a static method with the same name as the parent class to hide the static method * * of the parent class in the subclass (super and this cannot be used in static methods)**
  5. Private methods of a parent class cannot be overridden by subclasses (private decorated)

Upper Code:

1: Define a class with name and age attributes and get/set methods respectively. The member method outputs name and age:

public class Person {
    private String name;
    private int age;

    //get/ste method
    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;
    }
    //Member method:
    public void print(){
        System.out.println("My name is:"+this.name+","+"I this year:"+this.age+"year");
    }
}

2: Write a class that inherits the Person class. This class has its own sex attribute and provides get/set methods
And override the print method of the parent class to output name + age + gender

public class child extends Person{
    private String sex;      //The child class inherits the Person class, but also has its own attribute sex
    public void setSex(String sex){
        this.sex = sex;
    }
    public String getSex(){
        return sex;
    }
    @Override
    //Override the parent class method: because the parent class outputs the name and age, the name, age and gender should be output here
    public void print(){
        System.out.println("My name is:"+getName()+","+"I this year:"+getAge()+"year"+","+"I am"+sex+"children");
    }
}

3: Create a new test class to test the inheritance and rewriting of the two classes

//Test class,
public class Test {
    public static void main(String[] args) {
        child c = new child();
        c.setName("Xiao Hong");
        c.setAge(20);
        c.setSex("male");
        c.print();
    }
}
//Execute the set method of child inheriting person respectively, and use the rewritten method,
//The output result is: my name is Xiao Hong. I am 20 years old. I am a boy

super keyword:

  • super represents the parent object

How to use super:
1: super. The property name is used to call the instance variable of the same name hidden in the subclass.
2: super([parameter list)) is used to call the construction method of the parent class in the subclass construction method.

matters needing attention:

  1. The constructor of each subclass calls super() when it is not displayed. The system will provide a default super()
  2. super() is written on the first line
  3. You can call super() in the subclass constructor to complete the call to the constructor of a specific parent class

In short: super is to call the father's properties and methods to use
Upper Code:
1: Create a new class: define age as 20

public class super_test {
    public int age=20;
    public void print(){
        System.out.println(this.age);
    }
}

2: Create a second class and inherit the first class;

public class su2 extends super_test{
    public int age = 10;
    @Override
    public void print(){
        System.out.println(super.age);  //super is used here, which means that the age of the parent class is used
    }
}

3: Create test class:

public class test {
    public static void main(String[] args) {
    su2 s = new su2();
    s.print();
	}
}

In this way, the output is 20, which is the age of the parent class

The difference between this and super:

  1. super: it refers to the member in the direct parent class of the current object (used to access the member data or function in the hidden parent class in the direct parent class
    When the base class and the derived class have the same member definition, such as: super Variable name super Member function data name (argument)
  2. This: it represents the name of the current object (where ambiguity is easy to occur in the program, this should be used to indicate the current object; if the function
    The formal parameter has the same name as the member data in the class. In this case, this is required to indicate the member variable name
  3. super() is similar to this(). The difference is that super() calls the construction method of the parent class in the subclass. this() calls the class in this class.
    It is the construction method.
  4. Both super() and this() need to be placed in the first line of the constructor. Although one constructor can be called with this, two constructors cannot be called
  5. This and super cannot appear in one constructor at the same time, because this will inevitably call other constructors and other constructors
    Functions must also have super statements, so if there are the same statements in the same constructor, the meaning of the statements will be lost
    The compiler will not pass.
  6. Both this() and super() refer to objects, so they can't be used in static environment. include:
    Static variable, static method, static statement block.
  7. In essence, this is a pointer to this object, while super is a Java keyword.

This blog is relatively long and needs to be digested slowly. Many of them are high-frequency interview questions bye

Topics: Java Back-end