Interface and polymorphism in java learning
0x00 Preface
In the previous articles, we talked about encapsulation and inheritance. In this article, let's talk about the third largest object-oriented feature polymorphism. Before that, let's follow the abstraction of the previous article and take a look at the application of interfaces in Java.
0x01 interface
Interfaces in Java belong to reference data types and are collections of methods. If the class encapsulates member variables, construction methods and member methods, the interface mainly encapsulates methods, including abstract methods, default methods, static methods and private methods.
The definition of an interface is similar to that of a definition class. The interface keyword is required to define an interface. Although it will also be compiled into a class file, it is not a class, but another reference data type.
For the use of interfaces, like abstract classes, they cannot be created directly, but they can be implemented using the implements keyword. A class that implements an interface can be regarded as a subclass of the interface. It needs to implement all the abstract methods in the interface. If you create an object of this class, you can call the method, otherwise it must be an abstract subclass.
Define format:
public interface 接口名{
}
Abstract methods are modified with the abstract keyword, which can be omitted and have no method body. This method is used by subclass implementations.
public interface InterFaceName {
public abstract void method();
}
Default and static methods in the interface
Default method: use default for modification and cannot be omitted. It is provided to subclasses or subclass overrides.
Static method: use static modification to provide direct call to the interface.
public interface MyInterface {
public static void method(){
//执行语句
}
public default void method2(){
//执行语句
}
}
Private and static methods in interfaces
Private methods, like defining private variables, use private decoration to provide default methods and static method calls to interfaces.
pubilc interface InterfaceName{
}
Implementation interface
The relationship between a class and an interface is an implementation relationship, which is called a class implementation interface. This class can be called an implementation class of an interface. It is basically similar to an abstract class, and can also be called a subclass of an interface. The implemented actions are inherited and have almost the same format, but use the implements keyword instead of extensions.
接口代码:
public interface MyInterface {
void eat();
void sleep();
}
实现类代码:
public class Zi implements MyInterface {
@Override
public void eat() {
System.out.println("吃");
}
@Override
public void sleep() {
System.out.println("睡");
}
}
main方法代码:
public static void main(String[] args) {
Zi zi = new Zi();
zi.eat();
zi.sleep();
}
Interface default method code implementation:
定义接口:
public interface MyInterface {
default void eat() {
System.out.println("吃");
}
public default void sleep(){
System.out.println("睡");
}
}
实现类代码:
public class Zi implements MyInterface {
}
main方法代码:
public static void main(String[] args) {
Zi zi = new Zi();
zi.sleep();
zi.eat();
}
Here, the first method of the interface definition directly uses this keyword to define the default method. The second method can be written in both ways by adding public. The former is an ellipsis.
No code of the implementation class is written. Only one inheritance is written. The default method is defined by default. You can call it directly from the instantiated object without writing. Of course, you can rewrite it in the implementation class.
Interface static method usage
接口定义:
public interface MyInterface {
static void eat() {
System.out.println("吃");
}
}
实现类定义:
public class Zi implements MyInterface {
}
main方法代码:
public static void main(String[] args) {
MyInterface.eat();
}
Here you can see that in the main method, instantiating an object and accessing the eat method is an error. Methods defined as static must be accessed using the interface name.
Use of private methods
If an interface has multiple default methods and repeats, it can be extracted and encapsulated into private methods for the default method to call it.
public interface LiveAble {
default void func(){
func1();
func2();
} p
rivate void func1(){
System.out.println("跑起来~~~");
} p
rivate void func2(){
System.out.println("跑起来~~~");
}
}
This writing method is a new feature of jdk9, but jdk8 does not. This description is purely a copy.
0x02 multi interface implementation
As mentioned earlier, because Java only supports single inheritance, a class can only inherit one parent class. However, for interfaces, a class can implement multiple interfaces, which is called multiple implementation of interfaces, and a class can inherit one parent class and implement multiple interfaces at the same time.
Format:
class 类名 extends 父类名 impls 接口1,接口2{
...
}
或者
class 父类名 impls 接口1,接口2{
...
}
Interface multi implementation multi abstract method
If there is a method with the same name in multiple interfaces, the method with the same name only needs to be rewritten once.
Interface implements multiple default methods
Multiple default methods in the interface can be inherited and used by the implementation class. However, if there are methods with duplicate names, they must be rewritten once.
接口1:
public interface MyInterface {
default void method1(){
System.out.println("我是一个没有感情的默认方法");
}
}
接口2:
public interface MyInterface2 {
default void method1(){
System.out.println("我是一个没有感情的默认方法");
}
}
实现类:
public class Zi implements MyInterface,MyInterface1 {
@Override
public void method1() {
System.out.println("没有感情的方法");
}
}
main方法代码:
public static void main(String[] args) {
Zi zi = new Zi();
zi.method1();
}
The static methods in the interface will not have duplicate names. Static method access can directly use the interface name to access static methods.
Priority issues
If one parent class in a class implements multiple interfaces, the member party in the parent class and the default method in the interface have the same name, and the child class selects the nearest parent member method to execute.
matters needing attention:
0x03 polymorphism
Polymorphism is the third feature of object-oriented.
Polymorphic premise:
Format:
父类类型 变量名 = new 子类对象;
变量名.方法名();
Parent class type: refers to the parent class type inherited from the child class object or the implemented parent class interface type.
When calling a method in a polymorphic way, first check whether the method exists in the parent class. If not, the compilation error will occur; If so, the subclass overridden method is executed.
父类代码:
public abstract class Animal {
public abstract void play();
}
子类1代码:
public class Cat extends Animal {
@Override
public void play() {
System.out.println("撸猫");
}
}
子类2 代码:
public class Dog extends Animal{
@Override
public void play() {
System.out.println("撸狗");
}
}
main方法代码:
public static void main(String[] args) {
Animal cat = new Cat();
Animal dog = new Dog();
cat.play();
dog.play();
}
0x04 polymorphic reference type conversion
Polymorphic transformation can be divided into upward transformation and downward Transformation:
We often use upward transformation. Polymorphism itself is the process of upward transformation from subclass type to parent type.
When a parent class reference points to a child class object, this is an upward transformation. code:
Antmal cat = new Cat();
For a subclass object that has been transformed upward, the parent class reference can be transformed into a subclass reference. The format of forced type conversion can be used, that is, downward transformation.
Format:
子类类型 变量名 =(子类类型)父类变量名;
Here's why we use transformation
When calling a method in a polymorphic way, first check whether the method exists in the parent class. If not, the compilation error will occur. That is, you cannot call methods owned by a child class but not by a parent class. Compilation errors, let alone running. This is also a little "little trouble" brought to us by polymorphism. Therefore, if you want to call subclass specific methods, you must make a downward transformation.
父类代码:
public abstract class Animal {
public abstract void eat();
}
子类:
public class Cat extends Animal {
@Override
public void eat() {
System.out.println("吃鱼");
}
public void catchMouse(){
System.out.println("抓鱼");
}
}
main方法代码:
public static void main(String[] args) {
Animal cat = new Cat();
cat.eat();
Cat c =(Cat)cat;
c.catchMouse();
}
In order to avoid ClassCastException, Java provides the instanceof keyword to verify the type of reference variables. The format is as follows:
Therefore, we'd better make a judgment before the conversion.
public class Test {
public static void main(String[] args) {
// 向上转型
Animal a = new Cat();
a.eat(); // 调用的是 Cat 的 eat
// 向下转型
if (a instanceof Cat){
Cat c = (Cat)a;
c.catchMouse(); // 调用的是 Cat 的 catchMouse
} else if (a instanceof Dog){
Dog d = (Dog)a;
d.watchHouse(); // 调用的是 Dog 的 watchHouse
}
}
}
0x05 end
Interface and polymorphic chapter update are completed, and a small summary is detected every day.