Interface and polymorphism
Article directory
Interface
Interface Overview
When an abstract class, if all the methods in the abstract class are abstract, then we can define it as an interface, which is an abstraction of behavior. Class is an abstraction of properties and behaviors.
grammar
public interface interface name{
/ / interface members
}
Characteristics of the interface
1. The definition of the method in the interface does not need to be modified by abstract. It is abstract by default
2. An interface cannot be instantiated. A class is required to implement the interface
3. Methods in the interface cannot coexist with private, static and final
4. You can define "attribute" in the interface, which can be accessed through the instance of the implementation class of the interface (not recommended). It is recommended to use the interface name. Constant. This is a constant, which is public, static, final by default
Note: the specification of constant definition and naming should use uppercase, and the words should be separated by "_".
5. Interface can inherit interface (multiple inheritance)
Inheritance and implementation of interface
Interface can inherit more, that is, interface can inherit interface
[modifier] interface name extends parent interface 1, parent interface 2{
Constant definition
Method definition
}
Syntax to implement the interface:
public class class name implements interface name, interface name {
/ / implement the methods in each interface
}
Application of interface
Use the interface method to calculate the area and perimeter of circles and squares.
interface Cal{ /** Define pi */ public static final double PI = 3.14; /** Circumference */ public double getLong(); /** Area requirement */ public double getArea(); } class Rect implements Cal{ //Side length double r; public Rect(double r){ this.r = r; } public double getLong(){ return 4*r; } public double getArea(){ return r*r; } } class Circle implements Cal{ //radius double r; public Circle(double r){ this.r = r; } public double getLong(){ return 2*Cal.PI *r; } public double getArea(){ return Cal.PI * r *r; } } public class TestCal{ public static void main(String[] args){ //Create a square Rect rect = new Rect(10.0); double rectLong = rect.getLong(); double rectArea = rect.getArea(); System.out.println("The circumference of a square is:"+rectLong); System.out.println("The square area is:"+rectArea); //Create a circle Circle c = new Circle(10.0); double cLong = c.getLong(); double cArea = c.getArea(); System.out.println("The circumference of the circle is:"+cLong); System.out.println("The area of the circle is:"+cArea); } //The circumference of the square is: 40.0 //The square area is: 100.0 //The circumference of the circle is 62.800000000004 //The area of the circle is: 314.0 }
Features of interface in jdk1.8
- Defining static methods in an interface
interface ArrayUtils{//Tools for traversing arrays public static void printArr(int[] arr){ for(int i = 0; i < arr.length; i++) System.out.print(arr[i]+"\t"); } } public class TestUtils{ public static void main(String[] args){ ArrayUtils.printArr(new int[]{1,2,3,4,5}); } //1 2 3 4 5 }
- Define the default method implementation in the interface
interface Person{ public default void learn(){ System.out.println("I'm a default implementation"); } } class Student implements Person{ /* public void learn(){ System.out.println("Students are learning mathematics); } */ } public class TestPerson{ public static void main(String[] args){ Student s = new Student(); s.learn(); } } //I'm a default implementation
Benefits of using interfaces
- The interface defines a standard, which can make our code develop in layers and modules.
- Reduce code coupling, improve code scalability and maintainability
- Interface improves the limitation of single inheritance.
The difference between interface and abstract class
1. Interface is the abstraction of behavior, including static method, abstract method and default method, and all methods in abstract class.
2. Neither the interface nor the abstract class can be instantiated. The interface needs the class to implement and then instantiate the implementation class. The abstract class needs the class to inherit and then instantiate the subclass.
3. Abstract classes can only be inherited by one, interfaces can inherit multiple interfaces (jdk1.7), and interfaces can also be implemented multiple times.
4. The "attribute" in the interface is of public static final type. There is no difference between the attribute in the abstract class and that in the ordinary class.
5. By default, the method in the interface does not need to add absact, and the abstract method in the abstract class needs to add abstract keyword.
polymorphic
Conversion between parent and child classes
-
Subclass to parent (transition up)
Subclasses can be automatically transformed into parents
class Person{ String name; public void eat(){ System.out.println(name+"Be at table"); } } class Student extends Person{ public void eat(){ System.out.println(name+"Eating fish"); } } public class TestPerson{ public static void main(String[] args){ //Subclass automatically converted to parent Person person = new Student(); person.name = "Zhang San"; person.eat();//Zhang San is eating fish } }
Characteristic:
-
If a subclass overwrites a method of a parent class, and the instance of the subclass is assigned to a reference of the parent class, the subclass is called when the overridden method is called through this reference.
-
A reference from a parent class to an instance of a child class cannot call the child's unique methods and properties.
-
If the parent-child class has an attribute with the same name, the reference of the parent class to the instance of the child class will call the parent class when calling this attribute, which should not be confused with the method.
-
Parent to child (transition down)
Characteristic:
-
Conversion of a parent to a child cannot be done automatically.
-
The precondition of converting a parent class to a subclass is that the real body of the parent class is this subclass. After returning to the subclass, you can access the methods and properties inside the subclass.
-
If the real body of the parent class is subclass B, it cannot be forced to subclass A, but can only be converted to B.
-
Abstract class as parent class also conforms to the above theory
-
Interface is also in full accordance with the above theory, but note that there is no attribute in the interface.
class Person{ String name; public void eat(){ System.out.println(name+"Be at table"); } } class Student extends Person{ public void eat(){ System.out.println(name+"Eating fish"); } public void learn(){ System.out.println(name+"I'm learning"); } } public class TestPerson{ public static void main(String[] args){ Person p = new Student(); p.name = "Zhang San"; //Coercive transformation Student student = (Student) p; student.eat();//Zhang San is eating fish student.learn();//Zhang San is learning } }
-
Polymorphic definition
The same event occurs on different objects and produces different results.
Polymorphism is the ability of behavior to perform multiple functions.
In programming terminology, it means that a specific type of variable can refer to different types of objects, and can automatically call the methods of the referenced objects, that is, respond to different operations according to different object types.
There are three necessary conditions for polymorphism: inheritance, rewriting, and parent class reference to subclass object
Advantages of polymorphism
-
Replaceability: polymorphism is replaceable for existing code.
-
Extensibility: polymorphism is extensible to code. Adding a new subclass does not affect the polymorphism, inheritance, and operation of other features of the existing class.
-
Interface: polymorphism is that the parent class provides a common interface to the child class, which is implemented by the child class.
-
Flexibility: the application of polymorphism embodies flexible and diverse operations, and improves the efficiency of use.
-
Simplification: polymorphism simplifies the code programming and modification process of application software.
Interface polymorphism
interface Person{ public void eat(); } class Student implements Person{ String name; public void eat(){ System.out.println(name+"Be at table"); } public void learn(){ System.out.println(name+"I'm learning"); } } public class TestPerson{ public static void main(String[] args){ Student s = new Student(); s.name = "Zhang San"; Person p = s; p.eat(); Student student = (Student) p; student.learn(); //Zhang San is eating //Zhang San is learning } }
Application of polymorphism
-
Use parent class as parameter of method
Example: if dog, cat and duck are adopted by a master, the master can control the behavior of all kinds of animal barking, and realize a master human. In this category, the method of controlling animal barking is defined.
//The main human race class Host{ //How to make animals bark public void letCry(Animal animal){ animal.cry(); } } class Animal{ public void cry(){ System.out.println("call"); } } class Dog extends Animal{ public void cry(){ System.out.println("dog's bark"); } } class Cat extends Animal{ public void cry(){ System.out.println("Cat cry"); } } class Duck extends Animal{ public void cry(){ System.out.println("quack of a duck"); } } public class Test { public static void main(String[] args) { Host host = new Host(); Animal animal; animal = new Dog(); host.letCry(animal);//Control dog bark animal = new Cat(); host.letCry(animal);//Control of cat calls animal = new Duck(); host.letCry(animal);//Control duck calls //dog's bark //Cat cry //quack of a duck } }
-
Use parent class as return value of method
//Animals class Animal{ public void cry(){ System.out.println("call"); } } class Dog extends Animal{ public void cry(){ System.out.println("dog's bark"); } } class Cat extends Animal{ public void cry(){ System.out.println("Cat cry"); } } class Duck extends Animal{ public void cry(){ System.out.println("quack of a duck"); } } //The main human race class Host{ //How to make animals bark public Animal letCry(String type){ Animal animal = new Animal(); if (type=="dog"){ animal = new Dog(); }else if (type=="cat"){ animal = new Cat(); }else if (type=="duck"){ animal = new Duck(); } return animal; } } public class Test { public static void main(String[] args) { Host host = new Host(); Animal animal; animal = host.letCry("dog"); animal.cry();//dog's bark animal = host.letCry("cat"); animal.cry();//Cat cry animal = host.letCry("duck"); animal.cry(); //quack of a duck } }