Java polymorphism
This is the 7th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.
About the author
- The authors introduce
🍓 Blog home page: author’s home page 🍓 Introduction: 🥇, a high quality creator in JAVA field, 🎓, a junior in college, participated in various provincial and national competitions and won a series of honors. 🍓 pay attention to me: pay attention to my learning materials, document download all have, regularly update the article every day, inspirational to do a JAVA senior program ape 👨💻.
polymorphism
Polymorphism is the last feature of object orientation, which itself is divided into two main aspects:
Method polymorphism: overloading and overwriting
1 overload: the same method name, according to the type and number of parameters to complete different functions;
2 overwrite: the same method, according to the operation of the subclass, the function is different.
Object polymorphism: conversion of parent-class objects.
1 upward transformation: Subclass object becomes parent object, parent object = subclass object automatic;
Subclass object = (subclass) Instance of the parent class, mandatory;
class A{
public void print(a){
System.out.println("A output"); }}class B extends A{
public void print(a){
System.out.println(Output "B"); }}public class TestDemo1{
public static void main(String args[]){
B b = new B();
/ / B outputb.print(); }}Copy the code
This operation mainly observes two points:
1 see which class is instantiated (new);
See if the new class overwrites the method called by the parent class.
upcasting
public class TestDemo1{
public static void main(String args[]){
A a = new B(); // Upward transition
/ / B outputa.print(); }}Copy the code
Downward transition
public class TestDemo1{
public static void main(String args[]){
A a = new B(); // Upward transition
B b = (B) a; // Downward transitionb.print(); }}Copy the code
public class TestDemo1{
public static void main(String args[]){
A a = new A(); // There is no transition
B b = (B) a; // Downward transitionb.print(); }}/* Exception in thread "main" java.lang.ClassCastException: A cannot be cast to B at DuoTaiXing.main(TestDemo1.java:14) */
Copy the code
The above program compiled without error, but executed with a “ClassCastException” error, indicating that two unrelated classes have been forced to convert objects to each other.
Factors of transformation:
1. In practical work, the upward transformation of the object is mainly used. After upward transformation, there are many methods based on the method of the parent class, but the specific implementation depends on whether the subclass overwrites this method; .
2. Downcast, because before you can do a downcast operation, you have to do an upcast to establish a connection between the two objects. Without this connection, you can’t do a downcast. Dishes need to be transformed downward.
3 no transition, in some resources less time, such as: mobile development.
class A{
public void print(a){
System.out.println("A output"); }}class B extends A{
public void print(a){
System.out.println(Output "B");
}
public void funB(a){
System.out.println("funB"); }}public class TestDemo1{
public static void main(String args[]){
A a = new B(); // Upward transition
System.out.println(a instanceof A);
System.out.println(a instanceof B);
if (a instanceofB){ B b = (B) a; b.funB(); }}}/*
true
true
funB
*/
Copy the code
In order to facilitate the operation in the future, when writing the code, try not to perform the downward transformation operation, subclass try not to expand the new method name (method name of the parent class does not have), according to the operation of the parent class definition to improve the method.
Example: Use the object to complete the upward transformation
class A{
public void print(a){
System.out.println("A output"); }}class B extends A{
public void print(a){
System.out.println(Output "B"); }}class C extends A{
public void print(a){
System.out.println(Output "C"); }}public class TestDemo2{
public static void main(String args[]){
fun(new B());
fun(new C());
}
public static void fun(A a){ a.print(); }}Copy the code
In this way, the type is unified, even if there are more subclasses, methods or classes do not need to be modified, but in this must be emphasized: in the process of subclass operation, as close as possible to the parent class.
After all the code, there will be object transformation problem, and upward transformation is the majority.
In all future development, it is impossible for one class to inherit from another already implemented class, as in previous programs. That is, a class cannot inherit from an already implemented class, only from abstract classes or implementation interfaces.
An abstract class
In future projects, you should never have a class that inherits an already implemented class.
The core nature of object polymorphism lies in method overwriting. Such operation is not required, so we must use our abstract class to enforce the requirements of subclass methods.
Basic concepts of abstract classes
Ordinary is a perfect function, can directly produce objects and can be used, the inside of the method are with the method of the body, and is the biggest characteristic of abstract class contains abstract methods, and the abstract methods is only a statement and unrealized (no way) method, and abstract definition method to use the abstract keyword is complete, The abstract method must be in the abstract class, which uses the abstract declaration.
abstract class A{
private String msg = "www.baidu.com";/ / property
public void print(a){ // Common method
System.out.println(msg);
}
//{} is the method body. All abstract methods do not contain a method body
public abstract void fun(a) ; // Abstract methods
}
public class ChouXiang{
public static void main(String args[]){
/* chouxiang.java :12: error: A is abstract; A A =new A(); ^ 1 error */
A a =newA(); }}Copy the code
Abstract analogy ordinary class more abstract methods, no special above.
Why can’t abstract methods instantiate objects?
Abstract classes contain abstract methods, and the biggest difference between abstract methods and ordinary methods is that there is no method body, do not know the concrete implementation, and if the instantiation means that you can call all operations in the class.
Principles for using abstract classes:
- All abstract classes must contain subclasses
- Subclasses of an abstract class must override all of the abstract methods in the abstraction – method overrides must take into account permissions. Abstract methods can use any permissions, requiring as many permissions as possible public
- Abstract objects can be instantiated using subclasses through object polymorphism
abstract class A{
private String msg = "www.baidu.com";/ / property
public void print(a){ // Common method
System.out.println(msg);
}
//{} is the method body. All abstract methods do not contain a method body
public abstract void fun(a) ; // Abstract methods
}
// A subclass can only extend abstract classes using extends, so there is still a single inheritance limitation
class B extends A{// Define a subclass of the abstract class
public void fun(a){
System.out.println("Hello"); }}public class ChouXiang{
public static void main(String args[]){
A a =new B();// Upward transitiona.print(); a.fun(); }}Copy the code
Using one of the above programs, it is now clear that, unlike previous classes, abstract classes define methods that subclasses must override, which can optionally be overridden or not. And you can see that the abstract class actually has a few more abstract methods than the ordinary class, the other definition is exactly the same as the ordinary class. If the ordinary class is compared to a dish of cooked dishes, then the abstract class is a dish of half-finished products.
Some questions about abstract classes?
1. Can abstract classes use final definitions?
No, because classes defined by final cannot have subclasses, whereas abstract classes must have subclasses.
Can an abstract class contain a constructor?
Yes, because in addition to abstract methods, abstract classes also contain ordinary methods and properties, and properties must be initialized after the constructor is finished.
3. Can abstract classes not include abstract methods?
Yes, there can be no abstract methods in an abstract class, but conversely, if there is an abstraction, it must be an abstract class. Even if there is no abstract method in an abstract class, it cannot be instantiated directly.
Can abstract classes be declared static?
If you define an external abstract class, you cannot use the static declaration. If you define an inner class, the inner abstract class uses the static declaration to represent an external abstract class.
abstract class A{
private String str = "Hello,China";
static abstract class B{
public abstract void print(a); }}class C extends A.B{
public void print(a){
System.out.println("Hello China"); }}public class ChouXiang{
public static void main(String args[]){
A a =new B();// Upward transitiona.print(); }}Copy the code
Conclusion: If the constructor is not executed, the properties of the objects in the class must be the default values for their corresponding data types.
The most important feature of abstract classes is that they enforce the implementation structure of their subclasses.
interface
The most important feature of abstract classes and ordinary classes is that they agree on the implementation requirements of their subclasses. However, abstract classes have one disadvantage — the single inheritance limitation. If you want to require and avoid the single inheritance limitation, you need to use interfaces. In future development, interfaces take precedence. We can use both abstract classes and our interfaces in an operation.
Basic concepts of interfaces
An interface is a collection of abstract methods and global constants. It belongs to a special class. If a class is defined entirely by abstract methods and global constants, then it is called an interface, but the interface is defined using the interface keyword.
interface A{// Define the interface
public static final String INFO="Hello,World";
public abstract void print(a);
}
interface B{
public abstract void get(a);
}
Copy the code
Abstract methods also exist in interfaces. Obviously, an interface object cannot instantiate an object. Therefore, the principles for using interfaces are as follows:
1. Each interface must be subclassed, which implements the interface using the Implement keyword;
Subclasses of an interface (if not abstract classes) must override all abstract methods defined in the interface.
3. Instantiate the interface object by using the subclass of the interface and the upward transformation of the object.
In Java, each abstract class can implement multiple interfaces, but conversely, an interface can not inherit abstract classes, but in Java, an interface can inherit multiple interfaces at the same time, to achieve multiple interface inheritance operations.
// Because the definition of the interface and the class name requirements are the same, so to distinguish interface and class
// It is recommended to append the letter I to all interfaces
interface IMessage{
public static final String MSG = "www.baidu.com";
public abstract void print(a);// Abstract methods
}
interface INews{
public abstract String get(a);
}
class MessageImpl implements IMessage.INews{
public void print(a){
System.out.println("Print method in IMessage: +IMessage.MSG);
}
public String get(a){
return INews get method:+ IMessage.MSG; }}class NewsImpl implements INews{
public String get(a){
return null; }}public class InFa{
public static void main(String args[]){
IMessage ms = new MessageImpl();
//InFa
ms.print();
INews m = new MessageImpl();
// The get method in INews is www.baidu.com
System.out.println(m.get());
/* Exception in thread "main" java.lang.ClassCastException: NewsImpl cannot be cast to IMessage at infa.main (infa.java :33
INews mn = newNewsImpl(); IMessage m1 = (IMessage) mn; System.out.println(mn.get()); }}Copy the code
However, it is important to note that an interface consists entirely of abstract methods and global constants, so the end result of the following two defining interfaces in development is exactly the same:
Restrictions on the use of interfaces
Full definition:
interface A{
public static final String INFO="Interface is A";
public abstract void print(a);
}
Copy the code
Simplified definition:
interface A{// Define the interface
public String INFO="Interface is A";
public void print(a);
}
Copy the code
The interface has only one access permission :public, that is, if the interface method is not specified as public, it is still public.
- In the future, when writing interfaces, most interfaces will only provide abstract methods, and rarely see many global constants in the interface. In many cases, to avoid developer confusion, interface methods are added public.
- When a subclass implements an interface and extends an abstract class, use extends to extend an abstract class and implements multiple interfaces using implements.
// Because the definition of the interface and the class name requirements are the same, so to distinguish interface and class
// It is recommended to append the letter I to all interfaces
interface INews{
public String get(a);// Abstract methods
}
// This can be explicitly described in the class, and the following naming conventions are often used in future development
abstract class AbstractMessage{
// Only the abstract in the interface can be omitted, not the abstract class
public abstract void print(a);
}
class NewsImpl extends AbstractMessage implements INews{
public String get(a){
return "www.baidu.com";
}
public void print(a){} // The method body is called overwrite
}
public class InFa1{
public static void main(String args[]){
INews news = new NewsImpl();
System.out.println(news.get());
//NewsImpl is a common subclass of abstract classes and interfacesAbstractMessage am = (AbstractMessage) news; am.print(); }}Copy the code
3. An abstract class can implement multiple interfaces using implements, but an interface cannot inherit an abstract class.
// Because the definition of the interface and the class name requirements are the same, so to distinguish interface and class
// It is recommended to append the letter I to all interfaces
interface INews{
public String get(a);// Abstract methods
}
// This can be explicitly described in the class, and the following naming conventions are often used in future development
abstract class AbstractMessage implements INews{
// Only the abstract in the interface can be omitted, not the abstract class
public abstract void print(a);
}
class NewsImpl extends AbstractMessage{
public String get(a){
return "www.baidu.com";
}
public void print(a){} // The method body is called overwrite
}
/* A call to this class is equivalent to a grandchild instantiating a grandchild to a son */
public class InFa1{
public static void main(String args[]){
INews news = new NewsImpl();
System.out.println(news.get());
//NewsImpl is a common subclass of abstract classes and interfacesAbstractMessage am = (AbstractMessage) news; am.print(); }}Copy the code
The relationship is actually three levels of inheritance.
Interfaces and abstract classes
// Because the definition of the interface and the class name requirements are the same, so to distinguish interface and class
// It is recommended to append the letter I to all interfaces
interface INews{
public String get(a);// Abstract methods
public void pirnt(a);
}
// Suppose an interface may have an infinite number of subclasses, but the implementation of a method is the same
abstract class AbstractMessage implements INews{
public void print(a){
System.out.println("www.baidu.com"); }}// NewsImpl is a subclass of the INews interface
class NewsImpl extends AbstractMessage implements INews{
public String get(a){
return "www.baidu.com";
}
public void print(a){} // The method body is called overwrite
}
/* A call to this class is equivalent to a grandchild instantiating a grandchild to a son */
public class InFa1{
public static void main(String args[]){
INews news = new NewsImpl();
System.out.println(news.get());
//NewsImpl is a common subclass of abstract classes and interfacesAbstractMessage am = (AbstractMessage) news; am.print(); }}Copy the code
4. An interface can inherit from multiple parent interfaces using extends.
interface A{
public void pirntA(a);
}
interface B{
public void pirntB(a);
}
interface C extends A.B{
public void pirntC(a);
}
class Impl implements C{
public void pirntA(a);
public void pirntB(a);
public void pirntC(a);
}
public class InFa1{
public static void main(String args[]){}}Copy the code
5. Interface A series of internal interfaces can be defined, including internal ordinary classes, internal abstract classes, and internal interfaces. A static internal interface is equivalent to an external interface
In development, inner classes are never limited by concept. Inner classes can be defined in a class, they can be abstracted in an abstract class, and they can be defined in an interface. In practice, however, it is rare for the user to define an internal abstract class or interface (seen in Android development), and static is used to define an internal interface.
interface A{
public void printA(a);
static interface B{ // External interface
public void printB(a); }}class X implements A.B{
public void printA(a){
System.out.println("A");
}
public void printB(a){
System.out.println("B"); }}public class Inter{
public static void main(String args[]){
A.B ab = newX(); ab.printB(); }}Copy the code
Define standards using interfaces
The above concept of interfaces is not difficult to understand, but it is important to emphasize that in practical development, interfaces have three main functions:
-
Establish operating standards;
-
Indicates an ability;
-
Expose server-side remote method attempts to the client.
Define USB interface:
interface USB{
public void install(a); // Install
public void work(a); // Work on it
}
Copy the code
Defining a USB subclass:
class Computer{
public void plugin(USB usb){ usb.install(); usb.work(); }}class Flash implements USB{
public void install(a){
System.out.println("Install usb drive");
}
public void work(a){
System.out.println("Flash drive to work."); }}class Printer implements USB{
public void install(a){
System.out.println("Install printer driver");
}
public void work(a){
System.out.println("The printer works."); }}Copy the code
The source code:
interface USB{
public void install(a); // Install
public void work(a); // Work on it
}
class Computer{
public void plugin(USB usb){ usb.install(); usb.work(); }}class Flash implements USB{
public void install(a){
System.out.println("Install usb drive");
}
public void work(a){
System.out.println("Flash drive to work."); }}class Printer implements USB{
public void install(a){
System.out.println("Install printer driver");
}
public void work(a){
System.out.println("The printer works."); }}public class InFa3{
public static void main(String args[]){
/* Install usb drive usb drive to work install printer drive printer to work */
Computer cm = new Computer();
cm.plugin(new Flash());
cm.plugin(newPrinter()); }}Copy the code
It was found that the combination of interface and object polymorphism made the unification of parameters more explicit. And you can find the interface design on top of the class.
The difference between abstract classes and interfaces
The difference between | An abstract class | interface |
---|---|---|
Define keywords | Use abstract class for the declaration | Declare using interface |
composition | Global constants, global variables, constructors, abstract methods, ordinary methods | Global variables, abstract methods |
permissions | You can use any permissions | Only public permission can be used |
Relationship between | An abstract class can implement multiple interfaces | Interfaces cannot inherit from abstract classes, but can inherit from multiple interfaces |
use | Subclasses use extends | Subclass implements |
Design patterns | Template design pattern | Factory mode, agent mode |
limited | A subclass can inherit only one abstract method | A subclass can implement multiple interfaces |
It can be concluded from the above analysis that: In development, abstract classes and interfaces are in fact that can be used, and which are no clear limit, but an abstract class is one of the biggest weakness – a subclass can inherit an abstract class, there are the limitations of single inheritance, so when it comes to abstract classes and interfaces can be implemented, give priority to the interface, avoid single inheritance is limited.
Apart from the limitations of single inheritance, the use of abstract classes is actually similar to that of interfaces, but in real development, the design of abstract classes is more complex than that of interfaces.