In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article Xiaobian for you to introduce in detail "Java object-oriented programming polymorphism how to achieve", the content is detailed, the steps are clear, the details are handled properly, I hope this "Java object-oriented programming polymorphism how to achieve" article can help you solve doubts, following the editor's ideas slowly in-depth, together to learn new knowledge.
Polymorphisms of Java object-oriented programming. Understanding of polymorphism:
According to popular understanding, polymorphism is actually polysemy, that is, multiple states of a method, that is, different class objects that call the same method name have different implementation effects, such as the following code block:
Public class Test {public static void main (String [] args) {Dog dog = new Dog ("Doudou"); Cat cat = new Cat ("Huahua"); dog.eat (); cat.eat ();}}
Objects dog and cat both seem to call the eat method without passing parameters. In theory, the output should be the same, but in fact this is not the case. Let's take a look at the output:
This is a manifestation of polymorphism, in which different objects of different classes call the same method name, but have different implementation effects.
two。 The realization method of Polymorphism
Polymorphisms are implemented in Java through method rewriting (also known as method overwriting), method overloading, and interfaces (mainly relying on inheritance mechanism + method overwriting).
1. Method overload
Method overloading is easy to understand, that is, the method names of the subclass and the parent class are the same, but the number or type of parameters is different, and the return value is not required. I will not repeat it here.
two。 Method rewriting
For method rewriting, it is usually applied in the form of upward transformation and downward transformation, in which upward transformation is more common and downward transformation is relatively less used.
(1) upward transformation: that is, the subclass turns to the parent class. The biggest advantage of the upward transformation is that the parameters can be unified. The upward transformation can be shown in three places:
One: when an object is generated:
Note: the scope of methods that can be called by the instantiated object dog1 created in this form is determined by the parent class Animal, that is, only the methods in the Animal class can be called, not the methods unique to the subclass. only when the subclass has a method overridden to the parent class, the rewritten method of the subclass will be called!
Second, the transmission of method parameters:
Third: the transfer of the return value of the method.
The biggest advantage of upward transformation is that the parameters are unified, and the parent class reference can receive all objects of the subclass.
Look at the following example:
The complete code is:
Public class Animal {public String name; public Animal (String a) {name = a;} public void eat () {System.out.println ("food");} public static void fun (Animal animal) {animal.eat ();}} public class Dog extends Animal {public Dog (String name) {super (name) } public void eat () {System.out.println ("bone");}} public class Cat extends Animal {public Cat (String name) {super (name);} public void eat () {System.out.println ("fish");}} public class Test {public static void main (String [] args) {Dog dog = new Dog ("Doudou") Cat cat = new Cat ("Huahua"); dog.fun (dog); cat.fun (cat);}}
The result is:
Take it apart to analyze:
The argument to the fun method is the instantiated object of the Animal class
A subclass object of Animal, which can be passed in directly
In other words, for all subclass instantiated objects of the Animal class, parameters can be passed directly to the fun method, avoiding repetitive writing methods such as public static void fun (Dod d) {}, public static void fun (Cat a) {} and so on.
(2) downward transformation: upward transformation is a subclass to a parent class, and downward transformation is to restore the converted parent class to a subclass. The word restore is used here because the premise of the downward transformation is: when the upward transformation occurs first and we need to use a method unique to the subclass, we use the downward transformation. It is also easy to understand that the parent class is not necessarily a subclass, and only those transformed from the subclass can be converted downward. The form of downward transformation is as follows:
Animal animal = new Dog ("Doudou"); Dog dog = (Dog) animal
Basically similar to forced type conversion
Note: the downward transition is risky, and the conversion may not be successful. Here, you can refer to the instanceof class and judge with if statements to avoid reporting errors.
If (dog instanceof Dog) {}
(3) several points for attention in method rewriting:
Only member methods can be overridden, static static methods cannot be overridden, but method overloading can overload static methods
The subclass overrides the method, and the permission modifier of the subclass method > = the permission modifier of the parent method. At the same time, the subclass cannot override the private method of the parent class, and the package access modifier method of the parent class cannot be overridden by subclasses under different packages.
Methods modified with final cannot be overwritten (the String class in JDK is a final class)
The return value must be the same or upwardly transformed, that is, the return value of the overridden method can be a subclass of the return type of the parent method
Pay attention to the difference between method overwriting and method overloading: the method name of the subclass is the same as that of the parent class, and the parameters and return value types are the same. If only the return value type is different, the compilation will report an error.
You can use the @ override method to check whether the overwrite is the same
(4) finally, there is an example, which is easy to fall into a trap:
Public class A {public A () {this.func ();} public void func () {System.out.println ("A");}} class B extends A {private int num; public B (int num) {this.num = num;} public void func () {System.out.println ("B num==" + num) } public static void main (String [] args) {BB = new B; b.func ();}}
What will be output after the analysis is run?
Think carefully, be careful to fall into the trap, the answer is given at the end of the article.
3. Abstract class
For method overwriting, under general inheritance relations, subclasses can choose to override or not to overwrite, but in some scenarios, we want to make mandatory overwriting requirements for subclasses, which leads to the concept of abstract classes.
(1) Abstract class is modified with abstract. Abstract class is a superset of ordinary class. It just adds abstract methods on the basis of ordinary classes. Abstract methods have no method body, and the form is as follows:
(2) Abstract classes must have subclass inheritance.
(3) Abstract class cannot instantiate objects, only objects corresponding to subclass new can be used.
(4) the ordinary subclass inherits the abstract class and must override all the abstract methods. When the subclass is still an abstract class, you can choose not to override it and retain the abstract methods.
(5) the abstract modifier cannot be used with final or private.
4. Interface
Although the abstract class mentioned above can realize method overwriting, it is still defective. For example, abstract class still follows the principle of single inheritance, and a class can only inherit one abstract class. At the same time, semantically, as long as it inherits, it means An is B, which is sometimes illogical, so it leads to the concept of interface.
(1) definition and use of interface
We use the keyword interface to define the interface, and the subclass uses the keyword implements to implement the interface. At the same time, when naming the interface, we usually use the uppercase letter "I" to show the difference. For example, the interface name of the following code is IMessage, while for the subclass naming that implements the interface, we usually use Impl as the suffix.
(2) the characteristics of the interface:
There are only global constants and abstract methods in the interface (before JDK8, JDK8 extended the default method to understand it), such as:
Public interface IMessage {public static final int a = 10; public abstract void print ();}
There are only public permissions in the interface, and all of them are global constants and abstract methods. Therefore, public, static, final and abstract can be omitted in the interface, and these keywords are the default, so the previous code can be written directly as the following:
Public interface IMessage {int a = 10; void print ();}
There is no single inheritance limit for interfaces. Subclasses can implements multiple parent interfaces separated by commas, such as:
Public class CImpl implements IB,IMessage {public void print () {} public void printf () {}}
At the same time, there can be multiple inheritance between interfaces, and an interface can extends multiple parent interfaces.
An interface, like an abstract class, cannot instantiate an object directly. It must be instantiated by implementing its subclass.
If a subclass has both an inherited parent class and an implemented interface, it inherits the parent class before implementing the parent interface
(3) two common built-in interfaces of JDK
A:Comparable interface
When sorting using the Arrays.sort () method, when the sorting object is a custom class, the sort method does not know what attributes of the object should be sorted, so the custom class to be sorted needs to implement this interface and override the abstract method compareTo as follows:
Import java.util.Arrays;public class Person implements Comparable {/ / two attributes, name and age private String name; private int age;// have parameters to construct public Person (String name,int age) {this.name = name; this.age = age;} / / define the age of output public String toString () {return name + "is" + age " } / / override the compareTo method public int compareTo (Person o) {return (this.age-o.age);} public static void main (String [] args) {Person p1 = new Person ("Yan Xi", 18); Person p2 = new Person ("Wen Heng", 16); Person p3 = new Person ("Si Yi", 17); Person [] p = new Person [] {p1v p2v p3}} / / sort Arrays.sort (p) by sort method; System.out.println (Arrays.toString (p));}}
Output (in ascending order by age):
B: Cloneable interface
The Cloneable interface is located in the java.lang package. As the name implies, it is used for cloning. In the code, the new object is copied. The properties and methods of the new object are all copied from the original object. When implementing this interface, you only need to override the clone method provided by the Object class, as shown in the following example:
/ / implement Cloneable interface public class Animall implements Cloneable {private String name;// clone method protected Animall clone () throws CloneNotSupportedException {return (Animall) super.clone ();} public static void main (String [] args) throws CloneNotSupportedException {Animall A1 = new Animall (); a1.name = "Doudou"; / / a2 cloned from A1 Animall a2 = a1.clone () / / output a2, which is consistent with A1 System.out.println (a2.name); / / but A1 is not a2 System.out.println (A1 = = a2);}}
The results are as follows:
Add:
The Cloneable interface is a tagged interface, that is, it does not have any abstract methods. When a class implements this interface, it means that the class has the ability to clone.
The source code of the clone method is protected native object clone () throws CloneNotSupportedException;, where native is also a keyword, indicating that it is a local method, that is, the C++ method of the same name is called. Therefore, we can also find that the method modified by native has no method body.
What does not have a method body must be an abstract method ⅹ error, because native methods also have no method body.
Well, this is basically the content of polymorphism. Polymorphism in java mainly depends on inheritance and method overwriting, and for those methods that require mandatory overwriting, we lead to abstract classes, and in view of the limitations of abstract classes, we also learn interfaces. On the whole, there are so many details to pay attention to, and it is better to click on the code to understand.
Finally, the answer to the example in the article is presented:
Here comes the answer analysis.
Starting with the main method, the first sentence executed is B b = new B; because B inherits from A, the constructor of B should first execute the constructor of A, public A () {this.func ();}, note here that although it is the construction of A, the object is B, so the this,func () here is actually B.func (), public void func () {System.out.println ("B's num==" + num);}
Because num has not been successfully assigned here, num still has a default value of 0, so it outputs the num = = 0 of the first sentence of the answer, then executes the construction method of B, assigns 100 to num, and finally executes b.func, which outputs the num = = 100 of the second sentence of the answer.
Read here, this article "how to achieve polymorphism of Java object-oriented programming" article has been introduced, want to master the knowledge of this article also need to practice and use to understand, if you want to know more about the article, welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.