Learning notes -- Java object-oriented inheritance

Java object-oriented inheritance

inherit

  • Inheritance is one of the three characteristics of object-oriented

  • Basic functions of inheritance: code reuse; Important role: only with inheritance can there be "method coverage" and "polymorphism" in the future

  • Inherited syntax format:

      [Modifier list] class Class name extends Parent class name{
          Class body
      }
    
  • Inheritance in the Java language only supports single inheritance

  • Terminology:

    Class B inherits class A, where:

    • Class A is called: parent class, base class, superclass and superclass
    • Class B is called subclass, derived class and subclass
  • Java language subclass inherits parent class:

    • Private not supported
    • Construction method is not supported
    • Other data can be inherited
  • It is assumed that the Java language inherits any classes that are not displayed. By default, it inherits Java provided by the JavaSE library Lang.Object class

public class ExtendsTest01 {

    public static void main(String[] args) {
        
        C c1 = new C();

        c1.doSome();    // The doSome method called here inherits from class B
    }
}

class A{
    public void doSome() {
        System.out.println("do some !");
    }
}

class B extends A{

}

class C extends B{

}

Method coverage

[review] method overloading in Java:

  • Method overloading is called Overload

  • When can I use it

    In the same class, the functions of the methods are similar. It is suggested that the methods have the same name

  • What conditions constitute method overloading

    • In the same class
    • Same method name
    • Different parameter lists: type, order and number
  • What does method overloading have to do with

    • Method is independent of the return value type
    • Method is independent of the modifier list

[positive] method coverage

  • Method override is also called method override

  • When to use method overrides

    When the methods in the parent class can no longer meet the needs of the current subclass, it is necessary for the subclass to rewrite the inherited methods in the parent class. This process is called method rewriting / method overriding

  • What conditions does the code meet to trigger method override?

    • Occurs between parent and child classes with inheritance
    • The return value type is the same, the method name is the same, and the shape parameter list is the same
    • Access rights cannot be lower, but higher
    • Throw no more exceptions or fewer exceptions
  • Method: it is suggested to copy the past and change it again [prevent writing mistakes]

  • be careful:

    • Private methods cannot inherit, so they cannot be overridden
    • Constructors cannot inherit, so they cannot be overridden
    • There is no coverage for static methods [more details later]
    • Coverage is only for methods, not attributes
// Create animal class
public class Animal {
    
    public void move() {
        System.out.println("Animals are moving");
    }
}
// Create cat class
public class Cat extends Animal{
    
    // Re parent method
    public void move() {
        System.out.println("The cat is walking a cat step");
    }
}
// Create birds
public class Bird extends Animal{
    
    // Re parent method
    public void move() {
        System.out.println("Birds are flying");
    }
}
public class OverrideTest01 {
    
    public static void main(String[] args) {
        
        // Create animal objects
        Animal a = new Animal();
        a.move();

        // Create cat object
        Cat c = new Cat();
        c.move();

        // Create a bird object
        Bird b = new Bird();
        b.move();
    }
}

polymorphic

Polymorphic mechanism in Java [basic rules]

Polymorphism:

Reduce the coupling degree of the program [decoupling] and improve the expandability of the program [use as much as possible]

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

  • Concepts involved in polymorphism:

    • Upcasting

      • Subtype -- > parent type

        Also known as: automatic type conversion

      • There will be no problem through operation

    • Downcasting

      • Parent type -- > subtype

        Also known as: mandatory type conversion [mandatory type converter required]

      • Problems may occur through running [Famous exception: java.lang.ClassCastException]

    • Whether it is upcasting or downcasting, there must be an inheritance relationship between the two types. Cannot compile without inheritance

    • When the called method is specific to the subtype, it does not exist in the parent type. Downward casting is necessary

    • How to avoid ClassCastException exception in downcasting

      Using the instanceof operator

        (quote instanceof Data type name)
      

      The calculation result is Boolean

      • true: indicates that the object pointed to by this reference is this data type
      • false: indicates that the object pointed to by this reference is not of this data type
    • The Java specification requires that before using forced type conversion, it is recommended to use the instanceof operator to avoid ClassCastException exceptions

Relationship among Animal, Cat and Bird:

  • Cat inherits Animal
  • Bird inherits Animal
  • Cat has no inheritance relationship with Bird
// Create animal class
public class Animal {
    
    public void move() {
        System.out.println("Animals are moving");
    }
}
// Create cat class
public class Cat extends Animal{
    
    // Re parent method
    public void move() {
        System.out.println("The cat is walking a cat step");
    }

    // Is not a method inherited from a parent class
    // This method is a subclass object specific behavior
    public void catchMouse() {
        System.out.println("Cat catches mouse");
    }
}
// Create birds
public class Bird extends Animal{
    
    // Re parent method
    public void move() {
        System.out.println("Birds are flying");
    }

    // Subclass object specific behavior
    public void fly() {
        System.out.println("Bird fly !");
    }
}
public class Test {
    
    public static void main(String[] args) {
        
        // Previously written program

        // Create animal objects
        Animal a1 = new Animal();
        a1.move();

        // Create cat object
        Cat c1 = new Cat();
        c1.move();
        c1.catchMouse();

        // Create a bird object
        Bird b1 = new Bird();
        b1.move();

        // Use dynamic mechanism
        System.out.println("-----The following uses dynamic mechanisms----");

        Animal a2 = new Cat();  // Imagine long num = 10;
        // Cat is a Animal
        // The object type created by new Cat() is Cat, and the data type referenced by a2 in Animal a2 is Animal. It can be seen that they perform type conversion
        // Subtypes convert parent types, called upcasting, or automatic type conversion

        // Bird b2 = new Cat();     Bird has no inheritance relationship with cat
        

        // The compiler will only treat a2 type as Animal
        // Runtime is to look at the actual content of the underlying
        a2.move();  // The cat is walking a cat step

        // a2.catchMouse();      report errors
        // The compiler checks that it is of Animal type, and there is no catchMouse() method in Animal, resulting in static binding failure


        // Requirement: you need a2 to execute the catchMouse() method
        // You can use downcasting and forced conversion. You also need an inheritance relationship between the two
        Cat c2 = (Cat)a2;
        c2.catchMouse();



        // The parent type reference points to the sub type object [polymorphic]
        // The following programs are compiled without errors. The syntax allows, but the runtime reports an error. The JVM heap memory actually exists as a Bird object
        // There is no inheritance relationship between types, and a famous exception occurs: Java lang.ClassCastException
        // The trigger is usually in downcasting. Be careful

        // Animal  a3 = new Bird();
        // Cat c3 = (Cat)a3;

        // c3.catchMouse();  Error reporting: Java lang.ClassCastException

        // Avoid ClassCastException
        Animal  a3 = new Bird();

        if(a3 instanceof Cat) {
            Cat c3 = (Cat)a3;
            c3.catchMouse();
        }else if(a3 instanceof Bird){
            Bird b3 = (Bird)a3;
            b3.fly();
        }

    }
}

  1. java programs are always compiled and run in stages
  2. First analyze the compilation stage, and then analyze the operation stage. The compilation cannot pass and cannot run at all
  3. At the compilation stage, the compiler checks a2 that the data type of this reference is Animal, because Animal There is a move() method in the class bytecode, so the compilation passes. This process is called static binding and binding at the compilation stage. Only after the static binding is successful can the program run
  4. In the running phase of the program, if the real object created in the JVM heap memory is a Cat object, A2 move(); The move () method of Cat object must be called [method rewriting independent], which is called dynamic binding and runtime binding
  5. Whether rewritten or not, the runtime is only associated with the underlying reality

The parent type reference points to the sub type object. This mechanism leads to two different forms of program binding in compilation stage and running stage. This mechanism can become a dynamic syntax mechanism

Keywords: Java

Added by phrater on Sat, 05 Feb 2022 12:15:34 +0200