Analysis of polymorphic usage examples in Java
This article illustrates the polymorphic usage in Java. Share with you for your reference. The specific analysis is as follows:
Polymorphism is the core feature of object-oriented programming language. Encapsulation and inheritance are relatively simple, so here is only a small note on polymorphism...
1. What is polymorphism?
Polymorphism means that an object can have multiple features and show different states under specific circumstances, so as to deal with different attributes and methods. In Java, polymorphic implementation refers to using the same implementation interface to implement different object instances.
For example, we define a Parent class, and then define a getName () method to return a string to define a member method doSomething (Parent obj), which is a Parent type. In this method, obj. is called. getName()。 Then define two classes a and B, both inherited from the parent class, and override the getname () method in the subclass. Finally, create an object objp of the parent class in the main method and call objp Dosomething () method and pass it references to class A and class B. Observe the output.
It can be seen that the dosomething method of the parent class polymorphically calls the getname method of the object we passed, rather than the getname method of the parent class itself.
2. Interface in Java
An interface in Java is a declaration of a series of methods. An interface has only the characteristics of methods, but no implementation of methods. These methods can be implemented elsewhere through specific classes. In Java, the keyword interface is used to declare an interface.
Examples of implementing polymorphism with interfaces:
@H_ 404_ 37@
As you can see, the name of class A is printed out.
PS: if a class does not implement all the methods in the interface, the class must be declared abstract. An abstract class is not allowed to instantiate objects.
I hope this article will be helpful to your Java programming.