Object oriented learning III (interface, polymorphism)

Interface

An interface is a convention specification, a collection of multiple abstract methods, which only defines the functions and does not realize the functions.
effect:
In order to formulate specifications, it embodies the idea of separating specifications from matters, and also reflects the characteristics of low coupling between components.
Coupling: distance between parts
Cohesion: the degree of cohesion within each part

be careful:

  • An interface can be considered as a special class. The class keyword is used when defining a class, and the interface keyword is used when defining an interface. Interface names generally start with I
    Syntax:
public interface Interface name{
	//Abstract method 1
	//Abstract method 2
	//Abstract method 3
	.....
}
  • The methods in the interface are public abstract methods. Starting from Java 8, Java supports the definition of implemented methods in the interface
public interface Iwalkable{
	void walk();
}
//Equivalent to
public interface Iwalkable{
	public abstract void walk();
}
public interface IWalkable {
	public abstract void walk();//Abstract method
    
    default void defaultMethod(){
        System.out.println("There is a default implementation method, Belong to object");
    }
    static void defaultMethod(){
        System.out.println("There is a default implementation method, Belong to class");
    }
}
  • Class can inherit, but cannot inherit more. Interfaces can inherit, and can inherit multiple interfaces, that is, an interface can inherit multiple interfaces at the same time,
public interface IAmphibiable  extends IWalkable,ISwimable{
}

Interface implementation class

Like abstract objects, interfaces cannot create objects. You must define a class to implement the interface and override this method. This class is called implementation class, and the relationship between classes and interfaces is called implementations

public class Class name implements Interface name{
	//Method in overlay interface
}

According to the method coverage principle: the access modifier of the subclass method must be greater than or equal to the access modifier of the parent class method. The methods in the interface are public modified, so the methods in the implementation class can only use public modification.

If you are creating an implementation class object, you should face interface programming at this time:

Interface name variable name = new Implementation class();

If you have both inheritance and interface implementation, you should write inheritance first.

public class Class name extends Parent class implements Interface name...{

}

polymorphic

public class Animal{}
public class Dog extends Animal{}
public class Cat extends Animal{}
public static void main(String[] args){
        Dog dog = new Dog();
        dog.eat();

        //Embodiment of polymorphism
        //Animal: compile type
        //Dog: operation type
        Animal d = new Dog();
        //During compilation, check whether there are methods called in Animal
        //If yes, compile it

        //At run time, first find out whether there are methods in the Dog, and execute if there are. If not, find methods in the parent class
        d.eat();
    }

Polymorphism occurs when the compile type and run type are inconsistent.
Note: the compiled type must be the parent class or interface of the run type

Polymorphism means that an object can have many forms:

Animal	a = null;
a   =  new    Dog();	//	a indicates the Dog type at this time
a   =  new    Cat();	//	a now indicates the Cat type configuration
Operation inheritance relationship

The parent class reference variable points to the subclass object. When calling a method, it actually calls the subclass method

Interface variable name = new implementation class ();
Variable name Method ();

public class Animal{}
public class Dog extends Animal{}
public class Cat extends Animal{}
public class AnimalDemo {
	public static void main(String[] args) {
		// Create Cat objects
		Animal a = new Cat();
		a.shout();
		// Create a Dog object
		a = new Dog();
		a.shout();
	}
}
Operation implementation relationship

Interface variable name = new implementation class ();
Variable name Method ();

The problem of method call in polymorphism


It can be seen that at this time, the methods whose parent class does not exist but whose child class exists cannot be accessed through polymorphic methods, which leads to the following problems

Type conversion and instanceof operator

  • Automatic type conversion: assign subclass objects to parent variables
  • Cast type conversion: assign a parent type object to a child type variable (ClassCastException type conversion exception: when converting an object to an object with mismatched types)
public class Dog extends Animal{
    public void eat(){
        System.out.println("Eat shit");
    }
    public void sleep(){
        System.out.println("sleep");
    }
}
        Animal a = new Dog();
        a.eat();
        //Here we need to access the methods specific to the subclass
        //You need to convert the variable a of Animal type to the variable of Cat type
        Dog d1 =(Dog) a;
        d1.sleep();

instanseof:

 Cat c = (Cat)a;
        //Running error: ClassCastException type conversion exception.
        //An error will be reported when converting an object into an object whose type does not match

        //instanceof determines whether an object is an instance of a class
        //Syntax: object a instanceof class B;
        // Judge whether object A is an instance of class B? If yes, return true
        System.out.println(a instanceof Dog); //true
        System.out.println(a instanceof Animal);//true
        System.out.println(a instanceof Object); //true
        System.out.println(a instanceof Cat); //false

        if(a instanceof Cat){
            Cat c = (Cat)a;
        }

Benefits of polymorphism

Assign the implementation class object to the interface type variable to shield the implementation differences between different implementation classes, so as to achieve universal programming

Summary

  • Difference between interface and abstract class:
    1. Interfaces can be implemented more than one, and abstract classes can not inherit more than one
    2. All the methods in the interface are abstract methods. There can be either abstract methods or ordinary methods in abstract classes
  • Similarities between interfaces and abstract classes
    All specification constraints can be implemented
  • Syntax of interface and interface implementation class definition
    Interface: public interface interface interface name {}
    Generally speaking, the interface name starts with I
    Interface implementation class: public class class name (extends parent class name) implements interface name (, interface name) {}
  • What should be paid attention to when implementing an interface

Tags: Java

Posted by rachae1 on Tue, 24 May 2022 08:03:06 +0300