java basic syntax

This is the eighth part of my self-study of Java syntax.

This part mainly talks about the basic knowledge of inheritance, super, this and abstract classes.

inherit

definition

Inheritance: a subclass inherits the properties and behaviors of the parent class, so that the subclass object has the same properties and behaviors as the parent class. Subclasses can directly access non private properties and behaviors in the parent class.

benefit

  1. Improve code reusability.
  2. The relationship between classes is the premise of polymorphism.

Inherited format

With the extends keyword, you can declare that a subclass inherits another parent class. The definition format is as follows:

class Parent class {
	...
} 

class Subclass extends Parent class {
	...
}  

Inheritance demonstration, the code is as follows:

/ *
Define Employee class Employee,As parent class  
*/
class Employee {
    String name; // Define the name attribute
    // Define employee's working methods
    public void work() {
    	System.out.println("Work hard");
	}
}
/*
Define instructor class Teacher to inherit Employee class
*/
class Teacher extends Employee {
    // Define a method to print name
    public void printName() {
   		 System.out.println("name=" + name);
    }
} 
/*
Define test class
*/
public class ExtendDemo01 {
    public static void main(String[] args) {
        // Create an instructor class object
        Teacher t = new Teacher();
        // Assign a value to the name attribute of the Employee class
        t.name = "Xiao Ming";
        // Call the printName() method of the employee
        t.printName(); // name = Xiao Ming
        // Call the work() method inherited from the Teacher class
        t.work(); // Work hard
    }
}  

Inherited features - member variables

Member variables do not have the same name

If a member variable with no duplicate name appears in the parent class of the child class, the access will not be affected. The code is as follows:

class Fu {
    // Member variables in Fu.
    int num = 5;
} 
class Zi extends Fu {
    // Member variables in Zi
    int num2 = 6;
    // Member method in Zi
    public void show() {
    // Access num in the parent class,
        System.out.println("Fu num="+num); // Inherited, so direct access.
        // Access num2 in subclasses
        System.out.println("Zi num2="+num2);
    }
    }
	class ExtendDemo02 {
        public static void main(String[] args) {
        	// Create subclass objects
            Zi z = new Zi();
            // Call the show method in the subclass
            z.show();
    	}
	} 
Presentation results:
Fu num = 5
Zi num2 = 6

Duplicate member variable name

If a member variable with the same name appears in the parent class of the child class, the access will be affected. The code is as follows:

class Fu {
    // Member variables in Fu.
    int num = 5;
} 
class Zi extends Fu {
    // Member variables in Zi
    int num = 6;
    public void show() {
        // Access num in parent class
        System.out.println("Fu num=" + num);
        // Access num in subclass
        System.out.println("Zi num=" + num);
	}
}
class ExtendsDemo03 {
    public static void main(String[] args) {
    // Create subclass objects
    Zi z = new Zi();
    // Call the show method in the subclass
    z.show();
    }
} 
Presentation results:
Fu num = 6
Zi num = 6  

When a member variable with the same name appears in the child parent class, you need to use the super keyword to modify the parent member variable when you need to access the non private member variable in the parent class in the child class, similar to this learned before.

Use format:

super.Parent member variable name  

The subclass method needs to be modified, and the code is as follows:

class Zi extends Fu {
    // Member variables in Zi
    int num = 6;
    public void show() {
        //Access num in parent class
        System.out.println("Fu num=" + super.num);
        //Access num in subclass
        System.out.println("Zi num=" + this.num);
    }
} 
Presentation results:
Fu num = 5
Zi num = 6  

Tip: the member variables in Fu class are non private and can be accessed directly in subclasses. If member variables in Fu class are private, subclasses cannot be accessed directly. Usually, when coding, we follow the principle of encapsulation and use private to modify member variables. How to access the private member variables of the parent class? yes! You can provide public getXxx methods and setXxx methods in the parent class

Characteristics after inheritance -- member method

The member method does not have the same name

If there is a member method with no duplicate name in the parent class of the child class, the call will not be affected. When an object calls a method, it will first find out whether there is a corresponding method in the subclass. If there is a method in the subclass, it will execute the method in the subclass. If there is no method in the subclass, it will execute the corresponding method in the parent class. The code is as follows:

class Fu{
    public void show(){
    	System.out.println("Fu Class show Method execution");
    }
} 
class Zi extends Fu{
    public void show2(){
    	System.out.println("Zi Class show2 Method execution");
    }
    } 
	public class ExtendsDemo04{
        public static void main(String[] args) {
            Zi z = new Zi();
            //There is no show method in the subclass, but the parent method can be found to execute z.show();
            z.show2();
        }
	}   

Duplicate member method name -- override

If a member method with the same name appears in the parent class of a child class, the access is a special case, which is called method override.

  • Method overwrite: as like as two peas in the subclass, the same method is applied to the parent class (the return value type, the method name and the parameter list are the same), and the coverage effect will also appear, also known as rewriting or copying. The declaration remains unchanged and re implemented.

The code is as follows:

class Fu {
    public void show() {
    System.out.println("Fu show");
}
} 
class Zi extends Fu {
    //The subclass overrides the show method of the parent class
    public void show() {
    System.out.println("Zi show");
}
} 
public class ExtendsDemo05{
    public static void main(String[] args) {
        Zi z = new Zi();
        // There is a show method in the subclass. Only the rewritten show method is executed
        z.show(); // Zi show
    }
}  

Rewritten application

Subclasses can define their own behavior as needed. It not only follows the function name of the parent class, but also re implements the parent class method according to the needs of the child class, so as to expand and enhance. For example, the new mobile phone adds the function of caller ID avatar, and the code is as follows:

class Phone {
    public void sendMessage(){
    	System.out.println("send message");
    } 
    public void call(){
    	System.out.println("phone");
    } 
    public void showNum(){
    	System.out.println("Caller ID number");
    }
}  

//Smart phones
class NewPhone extends Phone {
    //Override the caller ID number function of the parent class, and add its own display name and picture function
    public void showNum(){
    	//Call the function whose parent class already exists and use super
        super.showNum();
        //Add your own unique function of displaying names and pictures
        System.out.println("Show caller name");
        System.out.println("Show Faces ");
    }
} 
public class ExtendsDemo06 {
    public static void main(String[] args) {
        // Create subclass objects
        NewPhone np = new NewPhone();
        // Call the method inherited from the parent class
        np.call();
        // Call the method overridden by the subclass
        np.showNum();
    }
}  

Tip: when rewriting here, use super A member method of a parent class, which means that the member method of the parent class is called.

matters needing attention

  1. If the subclass method overrides the parent method, the permission must be greater than or equal to the parent permission.
  2. As like as two peas, the subclass method covers the parent class method. The return value, function name and parameter list are exactly the same.

Characteristics after inheritance -- construction method

When there is a relationship between classes, what impact does the construction method in each class have?

First, we need to recall two things, the definition, format and function of construction methods.

  1. The constructor name is consistent with the class name. Therefore, a subclass cannot inherit the constructor of its parent class.

  2. Constructor is used to initialize member variables. Therefore, during the initialization of a subclass, the initialization of the parent class must be performed first. By default, there is a super() in the construction method of a subclass, which means that the construction method of the parent class is called. It can be used by the subclass only after the parent class member variable is initialized.

The code is as follows:

class Fu {
    private int n;
    Fu(){
    	System.out.println("Fu()");
    }
}  

class Zi extends Fu {
    Zi(){
        // super(), call the parent class constructor
        super();
        System.out.println("Zi()");
    }
} 
public class ExtendsDemo07{
    public static void main (String args[]){
        Zi zi = new Zi();
        }
    } 
Output results:
Fu()
Zi()  

super and this

Parent class space takes precedence over child class objects

Each time a subclass object is created, the parent class space is initialized first, and then the subclass object itself is created. The purpose is that if the subclass object contains its corresponding parent class space, it can contain the members of its parent class. If the parent class member is not private decorated, the subclass can use the parent class member at will. The code is reflected in that when the constructor of a subclass is called, the constructor of the parent class must be called first. The understanding diagram is as follows:

Meaning of super and this

  • super: represents the storage space ID of the parent class (which can be understood as the reference of the parent).
  • this: represents the reference of the current object (whoever invokes it represents who).

Usage of super and this

  1. Access member
this.Member variable ‐‐ Of this class
super.Member variable ‐‐ Parent class
this.Member's legal name() ‐‐ Of this class
super.Member's legal name() ‐‐ Parent class  

Usage demonstration, the code is as follows:

class Animal {
    public void eat() {
    	System.out.println("animal : eat");
    }
} 
class Cat extends Animal {
    public void eat() {
    System.out.println("cat : eat");
	} 
	public void eatTest() {
        this.eat(); // This calls the method of this class
        super.eat(); // super calls the method of the parent class
    }
} 
public class ExtendsDemo08 {
    public static void main(String[] args) {
        Animal a = new Animal();
        a.eat();
        Cat c = new Cat();
        c.eatTest();
    }
} 
The output result is:
animal : eat
cat : eat
animal : eat  
  1. Access construction method
this(...) ‐‐ Construction method of this class
super(...) ‐‐ Construction method of parent class  

Each construction method of a subclass has a default super(), which calls the null parameter construction of the parent class. Manually calling the parent class construct overrides the default super(). Both super() and this() must be in the first line of the constructor, so they cannot appear at the same time.

Characteristics of inheritance

  1. Java only supports single inheritance, not multiple inheritance
//A class can only have one parent class and cannot have more than one parent class.
class C extends A{} //ok
class C extends A,B... //error  
  1. Java supports multi-layer inheritance (inheritance system).
class A{}
class B extends A{}
class C extends B{}  

The top-level parent class is the Object class. All classes inherit Object by default as the parent class.

  1. Subclasses and superclasses are relative concepts.

abstract class

summary

origin

The method in the parent class is overridden by its subclasses, and the implementation of subclasses is different. Then the method declaration and method body of the parent class, only the declaration has meaning, while the method body has no meaning. We call methods without method bodies abstract methods. Java syntax stipulates that a class containing abstract methods is an abstract class.

definition

  • Abstract method: a method without a method body.
  • Abstract class: a class that contains abstract methods.

abstract use format

Abstract method

Using the abstract keyword to modify a method, the method becomes an abstract method. The abstract method contains only a method name and no method body.
Define format:

Modifier  abstract Return value type method name (parameter list);  

Code example:

public abstract void run();  

abstract class

If a class contains abstract methods, the class must be abstract.
Define format:

abstract class Class name {

}  

Code example:

public abstract class Animal {
	public abstract void run();
}  

Use of abstraction

Subclasses that inherit abstract classes must override all abstract methods of the parent class. Otherwise, the subclass must also be declared as an abstract class. Finally, a subclass must implement the abstract method of the parent class. Otherwise, objects cannot be created from the original parent class to the final subclass, which is meaningless.

Code example:

public class Cat extends Animal {
    public void run (){
    	System.out.println("The kitten is walking on the wall~~~");
    }
} 
public class CatTest {
        public static void main(String[] args) {
        // Create subclass objects
        Cat c = new Cat();
        // Call the run method
        c.run();
   		 }
}
Output results:
The kitten is walking on the wall~~~  

The method rewriting at this time is the completion and implementation of the parent class's abstract method by the subclass. The operation of rewriting this method is also called the implementation method.

matters needing attention

As for the use of abstract classes, the following are the details that should be paid attention to in syntax. Although there are many items, if you understand the essence of abstraction, you don't need to memorize by rote.

  1. An abstract class cannot create an object. If it is created, the compilation fails and an error is reported. Only objects whose non Abstract subclasses can be created.

    Understanding: suppose an object of an abstract class is created and an abstract method is called, but the abstract method has no specific method body and has no meaning.

  2. Abstract classes can have construction methods, which are used to initialize parent class members when subclasses create objects.

    Understanding: in the subclass constructor, there is a default super(), which needs to access the parent constructor.

  3. Abstract classes do not necessarily contain abstract methods, but classes with abstract methods must be abstract classes.

    Understanding: an abstract class that does not contain an abstract method is intended to prevent the caller from creating this class object. It is usually used for some special class structure design.

  4. A subclass of an abstract class must override all abstract methods in the abstract parent class. Otherwise, the compilation fails and an error is reported. Unless the subclass is also an abstract class.

    Understanding: assuming that all abstract methods are not overridden, the class may contain abstract methods. After creating objects, it is meaningless to call abstract methods.

Keywords: Java

Added by KefkaIIV on Sun, 09 Jan 2022 12:58:55 +0200