Chapter 5 note inheritance, interface and abstract class

Chapter 5 note inheritance, interface and abstract class

Section I succession

  • Subclasses inherit all properties and methods of the parent class (but cannot directly access private members)
  • According to the information hiding principle: the subclass will inherit all the methods of the parent class. Can be used directly
  • Subclasses can access the private member properties of the parent class by calling the methods of the parent class
  • With the same method name and parameters, the method of the subclass will have higher priority than the method of the parent class
  • Single root inheritance principle: each class can only inherit one class

  • Java all classes from Java Start with lang. object and build a type inheritance tree

class Human extends java.lang.Object
  • The Object class has clone, equals, finalize, getClass, hashCode, toString and other methods by default
  • Every Java class must have a constructor. If there is no constructor defined, the compiler will automatically generate an empty constructor with invisible parameters for the class
class A(){
    public A{}   //The compiler automatically generates an empty constructor without parameters
}
  • The first sentence of the constructor of each subclass calls the parameterless constructor super() of the parent class by default, unless the first sentence of the constructor of the subclass is super and the super statement must be placed in the first clause.
public class A {
	public A()
	{
		System.out.println("111111");
	}
	public A(int a)
	{
		System.out.println("222222");
	}
}
public class B extends A{
   public B()
   {
      //super();  The compiler automatically adds super(); Class B calls the parameterless function of class A
      System.out.println("333333");
   }
   public B(int a)
   {
      super(a);  //super() has been added, and in the first sentence, the compiler will not automatically add it; Class B calls the parametric function of class A
      System.out.println("444444");
   }
   public static void main(String[] a)
   {
      B obj1 = new B();
      System.out.println("==============");
      B obj2 = new B(10);       
   }

}
/* Operation results:
   111111
   333333
   ==============
   222222
   444444

Section 2 abstract classes and interfaces

abstract class

  • Class: attribute + method
  • A complete class: all methods are implemented (method body)
  • A complete method:
Method name(parameter)
{
  Method body
}
  • A class can have no methods, but if there are methods, they must be implemented, which is a complete class
  • A complete class can be instantiated new
  • If a class has a method that is not implemented temporarily, it needs to be defined as an abstract class

If the method has only the method name, formal parameter list and no method body, the class is defined as an abstract class

public abstract class Shape{
    int area;
    public abstract void claArea();
}
  • abstract class keyword abstract
  • Composition of abstract classes

- member variables, unlimited number

- specific methods, which can be implemented without limitation

- abstract method with abstract keyword, unlimited number

* * Tips: * * if a method is abstract, the class must also be abstract

  • Abstract classes are also classes. If a class inherits from an abstract class, it cannot inherit from other (Abstract) classes
  • Subclasses can also inherit abstract classes, but all abstract methods of the parent class must be implemented. If they cannot be fully implemented, they must be defined as abstract classes with the abstract keyword

Interface

  • If all the methods of a class are not implemented, the class is called an interface
public interface Animal{
    public void eat();
    public void drink();
}
  • A class can only inherit from one class, but it can implement multiple interfaces. Inheritance and implementation can be carried out at the same time

Extensions must be written before implement ation

  • To implement multiple interfaces, all methods defined in the interface must be implemented
  • Interface design makes up for the deficiency of single root inheritance

Similarities and differences between abstract classes and interfaces

Same point

  • Neither of them can be instantiated and new operation is not allowed

difference

  • abstract class, interface
  • Abstract classes can be implemented by some methods, but all methods of the interface cannot be implemented
  • A class can only inherit one (Abstract) class and implement multiple interfaces
  • Interfaces can inherit multiple interfaces
  • Abstract classes have constructors, while interfaces have no constructors
  • Abstract classes can have main or run, and the interface has no main function
  • Abstract class methods can have private/protected, and interface methods are public

Section III transformation, polymorphism and contract design

Class transformation

  • Types can be transformed to each other, but only limited to classes with inheritance relationships
    - a subclass can be converted to a parent class, while a parent class cannot be converted to a subclass
    - the subclass inherits all the method attributes of the parent class, and the subclass can become the parent class (from large to small, i.e. upward transformation); It is not allowed to directly change from a parent class to a child class (from small to large, i.e. downward transformation)

There is an exception when a parent class is converted to a child class, that is, the parent class itself is converted from a child class

Human obj1 = new Man();
Man obj2 = (Man) obj1;//obj1 itself originated from Man

polymorphic

  • The function of type conversion is polymorphism
  • Subclasses inherit all the methods of the parent class, but subclasses can redefine a method with the same name and parameters as the parent class

This behavior is rewriting (overwriting, overwriting), and overloading refers to the same function name and different formal parameters

  • The method of the subclass has priority over the parent class
public class Human {
	int height;    
    int weight;
    
    public void eat()  {
    	System.out.println("I can eat!");
    }
}

public class Man extends Human {
	public void eat() {
		System.out.println("I can eat more");
	}
	
	public void plough() { }

	public static void main(String[] a)	{
		Man obj1 = new Man();
		obj1.eat();   // call Man.eat()
		Human obj2 =  (Human) obj1;//Before the transformation of obj2, it was obj1 and Man, so the essence of obj2 is also Man
		obj2.eat();   // call Man.eat()
		Man obj3 = (Man) obj2;
		obj3.eat();	  // call Man.eat()
        
        obj1==obj2;//true
        obj1==obj3;//true
        //The three point to the same memory and call the same method eat
	}
}



  • Role of polymorphism
    Dynamically manipulate the same class of objects with different behaviors
    - decoupling between objects
public class AnimalTest {
   
   public static void haveLunch(Animal a) {
      a.eat(); //Animal does not have an eat method. It calls each element's own eat method
   }
   
   public static void main(String[] args) {
      Animal[] as = new Animal[4];
      as[0] = new Cat();  //Cat inherits from Animal, implements the interface of Animal, and makes an invisible class transformation
      as[1] = new Dog();
      as[2] = new Cat();
      as[3] = new Dog();
      
      for(int i=0;i<as.length;i++) {
         as[i].move();  //Animal does not have a move method. Call the move method of each element itself
      }
      for(int i=0;i<as.length;i++) {
         haveLunch(as[i]);
      }
      
      haveLunch(new Cat());  //Animal  a = new Cat();  haveLunch(a);
      haveLunch(new Dog());
      haveLunch(
            new Animal() //At the same time as the new interface, the interface methods are complemented and implemented to generate an anonymous subclass of Animal, which is used only once
            {
               public void eat() {
                  System.out.println("I can eat from an anonymous class");                  
               }
               public void move() {
                  System.out.println("I can move from an anonymous class");
               }
               
            });
   }
}
public interface Animal {
	public void eat();
	public void move();
}
public class Cat implements Animal
{
	public void eat() {
		System.out.println("Cat: I can eat");
	}
	
	public void move(){
		System.out.println("Cat: I can move");
	}
}
public class Dog implements Animal
{
	public void eat() {
		System.out.println("Dog: I can eat");
	}
	
	public void move() {
		System.out.println("Dog: I can move");
	}
}

Contract design

  • Contract: Specifies the behavior method that the object should contain
  • The interface defines the name, parameters and return value of the method, and standardizes the behavior of derived classes
  • Based on the interface, transformation and polymorphism are used to decouple the calling class from the standby class without affecting the call of the real method

Keywords: Java intellij-idea

Added by sharugan on Thu, 03 Mar 2022 17:29:26 +0200