Java syntax: inheritance and polymorphism

Introduction:

In Java, inheritance and polymorphism are two important concepts of object-oriented programming that allow us to create more flexible and extensible code. This article mainly introduces and explains the syntax and some details of inheritance and polymorphism.

Table of Contents

preface:

text:

1. Inheritance

1. Basic grammar

2. Characteristics of inheritance

3. Access member variables of the parent class in the subclass

4. Access the member methods of the parent class in the subclass

5.super keyword

6. Execution order of code

2. Polymorphism

1. Basic concepts:

2. Rewrite

3. Upward transformation

4. Downward transformation

5. Advantages and Disadvantages of Polymorphism

Summarize:


Text:

1.Inheritance

Inheritance is a mechanism in object-oriented programming that allows one class (called a subclass) to inherit the properties and methods of another class (called a parent class). Through inheritance, the subclass can obtain all the properties and methods of the parent class, and at the same time, it can add new properties and methods based on it, or modify the existing properties and methods. Generally speaking, inheritance is mainly used to extract commonalities between classes to achieve code reuse.

1. Basic syntax

In Java, inheritance is implemented using the keyword extends. Subclasses can inherit non-private properties and methods from the parent class. The basic inheritance syntax is as follows:

class ParentClass {
        // Attributes and methods of parent class
    
    }

    class ChildClass extends ParentClass {
        // Attributes and methods of subclasses
     
    }

It should be noted that the subclass will inherit the member variables or member methods in the parent class to the subclass. After the subclass inherits the parent class, it must add its own unique members to reflect the difference from the base class, otherwise there is no need to inherit.

2. Characteristics of inheritance

You must know that subclasses cannot inherit everything from the parent class and must follow certain rules.

For constructor methods:

A subclass cannot inherit the constructor of the parent class, but the subclass can call the constructor of the parent class to help the parent class initialize.

For member variables:

Subclasses can inherit all member variables of the parent class.

For member methods:

Subclasses can inherit non-private member methods, but they cannot inherit private member methods.

Here are some important features about inheritance in Java:

  • Subclasses can inherit the non-private properties and methods of the parent class, which means that the subclass can directly access the properties and methods of the parent class.
  • Subclasses can override parent class methods to override parent class methods.
  • Multiple inheritance is not supported in Java, and a class can only have one direct parent class.
  • A subclass can call the parent class’s constructor to initialize the properties of the parent class.
  • Subclasses can add new properties and methods based on inheriting from the parent class, thereby extending the code.
3. Access the member variables of the parent class in the subclass
  • When there are no variables with the same name in the subclass and parent class:
class ParentClass {
        // Attributes and methods of parent class
        int a;
        int b;
    }

    class ChildClass extends ParentClass {
        // Attributes and methods of subclasses
        int c;

        public void method() {
            a = 10; // Access a inherited from the parent class
            b = 20; //Access b inherited from the parent class
            c = 30; // Access the subclass’s own c
        }
    }

In Java, if there are no variables with the same name in the subclass and the parent class, the subclass can directly use the member variables of the parent class. This is because the subclass will inherit the variables of the parent class and can directly use the variables of the parent class even if there is no variable with the same name.

  • When there are member variables with the same name in the subclass and parent class:
public class Base {
        int a;
        int b;
        int c;
    }
    //------------------------------------------------ ----------------

    public class Derived extends Base{
        int a; // Same name as member a in the parent class and the same type
        char b; // Same name as member b in the parent class, but different type
        public void method(){
            a = 100; // The member variable being accessed has the same name as the member variable in the parent class, and your own is accessed first.
            b = 101; // If the accessed member variable does not exist in the subclass, then access the member variable inherited from the parent class.
            c = 102; // The subclass does not have c, and the access must be the c inherited from the parent class.
            // d = 103; // Compilation failed because neither the parent class nor the subclass defined member variable b
        }
    }

Follow the following points when accessing members through subclass objects:

  • If the member variable to be accessed exists in a subclass, access your own member variable first.
  • If the member variable being accessed does not exist in the subclass, it will be accessed inherited from the parent class. If the parent class is not defined, a compilation error will be reported.
  • If the member variable being accessed has the same name as a member variable in the parent class, your own will be accessed first.
  • Member variable access follows the principle of proximity. If you have one, you have priority. If not, you will find it in the parent class.
4. Access the member methods of the parent class in the subclass
  • When the member method names of the subclass and parent class are different:
class Parent {
    public void display() {
        System.out.println("This is the display method in the Parent class");
    }
}

class Child extends Parent {
    public void callParentMethod() {
        display(); // The subclass directly calls the member method of the parent class
    }
}

public class Main {
    public static void main(String[] args) {
        Child child = new Child();
        child.callParentMethod(); // Output: This is the display method in the Parent class
    }
}

Like member variables, if there is no method with the same name in the subclass and parent class, the subclass can directly use the member method of the parent class. When accessing a method in a subclass method or through a subclass object, access your own method first. If you don’t find it yourself, you will look for it in the parent class. If it doesn’t exist in the parent class, an error will be reported.

  • When the subclass and parent class member method names are the same:
 public class Base {
        public void methodA(){
            System.out.println("methodA() in Base");
        }
        public void methodB(){
            System.out.println("methodB() in Base");
        }
    }
    public class Derived extends Base{
        public void methodA(int a) {
            System.out.println("method(int) method in Derived");
        }
        public void methodB(){
            System.out.println("methodB() method in Derived");
        }
        public void methodC(){
            methodA(); // No parameters are passed, access methodA() in the parent class
            methodA(20); // Pass the int parameter and access methodA(int) in the subclass
            methodB(); // If accessed directly, the methodB() in the subclass will always be accessed, and the base class cannot be accessed.
        }
    }

When accessing methods with different names in the parent class and the subclass through the subclass object, the method is first searched in the subclass and accessed if found. Otherwise, the method is searched in the parent class and accessed if found. Otherwise, a compilation error is reported.
When accessing the method with the same name of the parent class and the subclass through the derived class object, if the parameter list of the method with the same name of the parent class and the subclass is different (overloaded), select the appropriate method to access according to the parameters passed by the calling method, if not, an error will be reported;

It can be seen that member methods are consistent with variables and have priority in accessing subclasses. However, we can specify that they have priority in accessing parent classes. We can achieve this through the super keyword.

5.super keyword

The super keyword is used in Java to refer to the direct parent class of an object. It can be used to call the constructor of the parent class, access the member variables and member methods of the parent class, and call the parent class in the subclass. Constructors and member methods. We can access the member methods and variables of the parent class through super.

 public class Base {
        int a;
      
        public void methodA(){
            System.out.println("methodA() in Base");
        }
        public void methodB(){
            System.out.println("methodB() in Base");
        }
    }
    public class Derived extends Base{
        int a;
        
        public void methodB(){
            System.out.println("methodB() method in Derived");
        }
        public void methodC(){
            a=10;//Direct access, all variables accessed are in subclasses
            super.a=10;//super call, accessing the member variables of the parent class
            
            methodA(); // The subclass does not have a method to access the parent class
            methodB(); // Direct access, all accessed are methodB() in the subclass, and those in the base class cannot be accessed
            super.methodB();//super call, accessing the member methods of the parent class

        }
    }

In a subclass, if you want to explicitly access members of the parent class, you can use the super keyword.

At the same time, we can also use super to call the constructor of the parent class:

Call the constructor of the parent class: Use super() in the constructor of the subclass to call the constructor of the parent class. You can use super() to call the parent class’s parameterless constructor, or you can use super(parameter list) to call the parent class’s parameterized constructor.

public class Child extends Parent {
    public Child() {
        super(); // Call the parent class’s no-argument constructor
    }
}

There are also some details in the construction method:

1. If the parent class explicitly defines a parameterless or default constructor, there is an implicit super() call by default in the first line of the subclass constructor, that is, the base class constructor is called.
2. If the parent class constructor has parameters, the user needs to explicitly define the constructor for the subclass and select the appropriate parent class constructor to call in the subclass constructor, otherwise the compilation will fail.
3. In the subclass constructor, when super(…) calls the parent class constructor, it must be the first statement in the subclass constructor.
4. super(…) can only appear once in the subclass constructor, and cannot appear at the same time as this.

It should be noted that super, like this, can only be used in non-static methods.

6. Execution order of code

In Java, when it comes to inheritance, the order in which code is executed follows these rules:

  1. Static code blocks and static variable initialization: First, the static code blocks and static variable initialization in each class will be executed in order from top to bottom in the inheritance hierarchy. This means that the static code blocks and static variables of the parent class will be initialized first, and then the static code blocks and static variables of the subclass.
  2. Parent class construction method: father-son-father-son, there is father first and then son. Then, the construction method of the parent class will be called. If the parent class has another parent class, the constructor method of the parent class will be called in sequence until the top-level parent class.
  3. Instance code block of parent class
  4. Initialization of subclass member variables and instance code blocks: Next, the member variables and instance code blocks of the subclass will be initialized and executed in the order of declaration.
  5. Subclass constructor: Finally, the constructor of the subclass is called.

Code verification:

class Person {
    public String name;
    public int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
        System.out.println("Person: Constructor execution");
    }

    {
        System.out.println("Person: Instance code block execution");
    }

    static {
        System.out.println("Person: static code block execution");
    }
}

class Student extends Person {
    public Student(String name, int age) {
        super(name, age);
        System.out.println("Student: Construction method execution");
    }

    {
        System.out.println("Student: Example code block execution");
    }

    static {
        System.out.println("Student: static code block execution");
    }
}

public class test {
    public static void main(String[] args) {
        Student student1 = new Student("Zhang San", 19);
        System.out.println("===========================");
        Student student2 = new Student("gaobo", 20);
    }


}

The result is as follows:

By analyzing the execution results, the following conclusions are drawn:
1. The static code block of the parent class takes precedence over the static code block of the subclass and is executed earliest.
2. The parent class instance code block and the parent class construction method are executed immediately.
3. The instance code block and subclass construction method of the subclass are executed immediately.
4. When the subclass object is instantiated for the second time, the static code blocks of the parent class and the subclass will no longer be executed.

2. Polymorphism

1.Basic concept:

Polymorphism means that a reference takes on different states through calls to different objects. Generally speaking, it is a variety of forms. The specific point is to complete a certain behavior. When different objects complete it, different states will be produced. One manifestation of polymorphism is that when the code is running, when objects of different classes are passed, methods in the corresponding classes will be called.

One form of polymorphism is:

Parent class type object name = subclass object;

For example:

class Person {
    
}

class Student extends Person {
   
}

public class test {
    public static void main(String[] args) {
      Person p = new Student();
    }


}

To achieve polymorphism in Java, the following conditions must be met, all of which are indispensable:

1. Must be under the inheritance system
2. Subclasses must rewrite methods in the parent class
3. Call the overridden method through the reference of the parent class

Here is an example of polymorphism:

//Define an animal class
class Animal {
    public void makeSound() {
        System.out.println("Animals make noises");
    }
}

//Define a dog class, inherited from the animal class
class Dog extends Animal {
    public void makeSound() {
        System.out.println("The dog barked");
    }
}

//Define a cat class, inherited from the animal class
class Cat extends Animal {
    public void makeSound() {
        System.out.println("The cat meows");
    }
}

public class PolymorphismExample {
    public static void main(String[] args) {
        Animal animal1 = new Dog(); // Use parent class reference to point to subclass object
        Animal animal2 = new Cat(); // Also use the parent class reference to point to another subclass object

        animal1.makeSound(); // Output: The dog barks
        animal2.makeSound(); // Output: The cat meows
    }
}

When the caller of the class writes the makeSound method, the parameter type is Animal (parent class). At this time, the method does not know or pay attention to which type (which subclass) instance the current reference points to. . At this time, this reference may have multiple different behaviors when calling the makeSound method (related to the instance referenced by a). This behavior is called polymorphism.

2.Rewrite

In Java, method overriding (Override) refers to a subclass redefining existing methods in the parent class to achieve specific functions. Method overriding is a way of achieving polymorphism that allows subclasses to provide custom implementations of inherited methods. When a subclass overrides a method of a parent class, when the subclass object calls the method, the implementation in the subclass will be executed, not the implementation in the parent class.

Here are some important rules and considerations for method overriding:

  • When a subclass overrides a parent class method, it must generally be consistent with the parent class method prototype: return value type, method name (parameter list) must be completely consistent
  • The return value type of the overridden method can be different, but it must have a parent-child relationship
  • Access rights cannot be lower than the access rights of the overridden method in the parent class. For example: If a parent class method is modified by public, the method overridden in the subclass cannot be declared as protected.
  • Methods and constructors modified by static or private in the parent class cannot be overridden.
  • Overridden methods can be explicitly specified using the @Override annotation. This annotation can help us perform some legality checks. For example, if the method name is accidentally spelled incorrectly (such as aet), then the compiler will You will find that there is no aet method in the parent class, and a compilation error will be reported, indicating that overriding cannot be constituted.

Here is a rewritten example:

// parent class
class Animal {
    public void makeSound() {
        System.out.println("Animals make noises");
    }

}

// Subclass
class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("The dog barked");
    }
}

public class OverrideExample {
    public static void main(String[] args) {
        Animal animal = new Dog(); // Use parent class reference to point to subclass object
        animal.makeSound(); // Output: The dog barks
    }
}

There are many similarities between rewriting and overloading. To prevent confusion, here is a summary.

The difference between rewriting and overloading:

  1. Overloaded methods define multiple methods in the same class, while overridden methods allow subclasses to redefine existing methods in the parent class.
  2. The method name of the overloaded method is the same, but the parameter list is different, while the method name, parameter list and value of the overridden method must be exactly the same as the overridden method in the parent class.
  3. The call to an overloaded method is determined based on the type and number of parameter lists, while the call to an overridden method is determined based on the actual type of the object.
  4. Overloading can modify the access qualifier, but the overridden access qualifier of the subclass must be greater than the parent class.
3. Upward transformation

Upcasting refers to the process of assigning an instance of a subclass to a parent class reference. In upward transformation, the instance of the subclass can be assigned to the reference variable of the parent class, so that the methods and properties of the subclass object can be accessed through the reference variable of the parent class. Upcasting is safe because the child class object has all the properties and methods of the parent class object, but cannot access the child class-specific methods and properties.

Example code:

class Animal {
    public void makeSound() {
        System.out.println("Animals make noises");
    }
}

class Dog extends Animal {
    public void makeSound() {
        System.out.println("The dog barked");
    }

    public void wagTail() {
        System.out.println("dog wagging its tail");
    }
}

public class UpcastingExample {
    public static void main(String[] args) {
        Animal animal = new Dog(); // Upward transformation
        animal.makeSound(); // Output: The dog barks
        // animal.wagTail(); // Compilation error, unable to access subclass-specific methods
    }
}

In this example, the instance of the subclass Dog is assigned to the reference variable of the parent class Animal, which is an upward transformation. By referencing the variable animal from the parent class, you can call the method makeSound overridden by the subclass, but you cannot access the subclass-specific method wagTail.

4.Downward transformation

Downcasting refers to the process of converting a parent class reference into a child class reference. In downcasting, you need to use cast to convert the parent class reference to the subclass reference in order to access the subclass-specific properties and methods. Downcasting is unsafe because the object pointed to by the parent class reference may not be an instance of the subclass, and a ClassCastException will be thrown if the cast fails.

Downcasting is rarely used and is unsafe. If the conversion fails, an exception will be thrown at runtime. In order to improve the security of downward transformation in Java, instanceof is introduced. The function of instanceof is to determine whether object is class or an instance of a subclass, if so, true is returned, otherwise false is returned. If object is null, then false is returned. The function is to determine whether object is an instance of class or a subclass. If so, it returns true, otherwise it returns false. If object is null, returns false. If the expression is true, it is safe to convert.

Example code:

public class DowncastingExample {
    public static void main(String[] args) {
        Animal animal = new Dog(); // Upward transformation
        if (animal instanceof Dog) {
            Dog dog = (Dog) animal; // Downcast
            dog.makeSound(); // Output: The dog barks
            dog.wagTail(); // Output: dog wagging its tail
        }
    }
}

In this example, animal instanceof Animal returns true because animal is an instance of the Animal class; animal instanceof Dog also returns true because animal is an instance of the Dog class.

5. Advantages and Disadvantages of Polymorphism

advantage:

  1. Flexibility: Polymorphism makes the code more flexible and able to adapt to different objects and scenarios. Through polymorphism, reference variables of the parent class type can be used to reference subclass objects, thereby achieving a unified interface to access different subclass objects, simplifying the design and implementation of code.

  2. Scalability: Polymorphism makes code easier to extend. When you need to add a new subclass, you don't need to modify the existing code. You only need to create a new subclass and implement the abstract method of the parent class, and you can use the new subclass object directly in the existing code.

  3. Maintainability: Polymorphism improves the maintainability of code. Through polymorphism, the code can be modularized, reducing the coupling between codes, making it easier to modify and maintain each module independently.

  4. It can reduce the "cyclomatic complexity" of the code and avoid using a lot of if-else

shortcoming:

  1. Performance loss: Polymorphism will bring certain performance loss. Since polymorphism requires the type of an object to be dynamically determined at runtime, additional runtime overhead is required, which may result in a certain performance loss.

  2. Reduced readability: Excessive use of polymorphism may reduce the readability of your code. If polymorphism is used excessively in code, it may make the code difficult to understand and maintain, reducing the readability of the code.

  3. Not suitable for all scenarios: Polymorphism is not suitable for all scenarios. There are situations where you need to know the exact type of an object explicitly, rather than using polymorphism. Excessive use of polymorphism may lead to increased complexity of the code, which is not conducive to understanding and maintenance.

Summary:

Inheritance: A class can inherit the properties and methods of another class, which can avoid repeated writing of similar code and can achieve multi-level class organization and management.

Polymorphism: allows different objects to respond differently to the same message. Through dynamic binding, the method to be called can be determined based on the actual type of the object, thereby achieving code flexibility and scalability.

syntaxbug.com © 2021 All Rights Reserved.