Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Object-oriented Polymorphic case Analysis of Java

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces "Java object-oriented polymorphic case analysis". In daily operation, I believe that many people have doubts about Java object-oriented polymorphic case analysis. The editor consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "Java object-oriented polymorphic case analysis". Next, please follow the editor to study!

Polymorphic understanding

What is polymorphism? Literally, it means a variety of forms, that is, objects instantiated by different classes call the same method, and it can also be understood that different types of objects produce different states through the same behavior, which is called polymorphism.

To understand polymorphism, we must understand the two key points of upward transformation and rewriting, and then deeply understand the concept of polymorphism. after looking at the concept of upward transformation and rewriting, you will suddenly become enlightened and understand a lot at once. Because the condition of polymorphism is upward transformation, rewriting and inheritance.

Upward transformation

First of all, the premise of polymorphism is inheritance, so since it is inheritance, there must be a relationship between parent and child classes.

Let's recall how to create subclass objects and parent objects.

Class Animal {public String name;// name public int age; public void eat () {System.out.println ("I want to eat!") ;} public void sleep () {System.out.println ("I want to sleep!") ;}} class Cat extends Animal {public void mew () {System.out.println ("Meow!!") ;} public class TestDemo1 {public static void main (String [] args) {Cat cat = new Cat (); / / instantiate the subclass object cat.name= "mimi"; Animal animal = new Animal (); / / instantiate the parent object animal.eat ();}}

Here you create the cat class and then inherit the Animal class. We can call methods and properties by instantiating cat and Animal objects.

Then what is upward transformation?

The reference of the original subclass object refers to the subclass object, now let the parent class reference the subclass object, which is the upward transformation.

Let's use the code to understand:

This is the upward transformation, and we can also use the animal as a parent class reference to call the method

At this point, we will find that we can use this reference to call the methods and properties of the parent class, but not the methods and properties of the subclass, so why? The reason is that because the parent class does not have a subclass, it cannot be called. Summary: during the upward transformation, that is, the parent class references the subclass object, this parent class reference can only call the properties and methods of the parent class, not the subclass.

Three forms of upward transformation

The first kind: direct assignment

That's the way we wrote it above:

Animal animal1 = new Cat (); / / the reference of the parent object refers to the subclass object-> upward transition Animal animal2 = new Dog ()

The second: as a method parameter:

The third is the return value:

Let's go back to what was the print result just now.

But what if I turn the parent method into eating cat food? The result, not surprisingly, is mimi. I want cat food.

But this gives rise to a problem, if I am creating a dog and then calling the eat method, does the dog have to eat cat food? There will be a problem, so we can write an eat method in the subclass.

Class Animal {public String name;// name public int age; public void eat () {System.out.println (this.name+ "want to eat!") ;} class Dog extends Animal {public void dark () {System.out.println ("Wang Wang!!") ;} public void eat () {System.out.println (this.name+ "eat dog food!") ;}} class Cat extends Animal {public void mew () {System.out.println ("Meow!!") ;} public void eat () {System.out.println (this.name+ "eat cat food!") ;} public class TestDemo1 {public static void main (String [] args) {/ / grammatical form: parent variable = new subclass (); Animal animal1 = new Cat (); / / references to parent objects refer to subclass objects-> upward transition Animal animal2 = new Dog () / / references to parent objects refer to subclass objects-- > upward transformation animal1.name = "kittens"; / / access parent properties animal2.name = "puppies"; / / access parent properties animal1.eat (); animal2.eat (); / / animal.mew (); / / access methods specific to subclasses}}

Another dog class is created, and then two eat methods are created in each of the two subclasses.

We found that at this time it became very clear and achieved the effect we wanted.

But we should also think about why we call the eat method of the child class instead of the parent class.

Dynamic binding and static binding

Dynamic binding actually happens at this time. We can look at the bytecode file and open the powershell window.

We all know that to execute a program is to compile and then run, and this is to call the eat method of Animal at compile time, and to call the method of Cat at run time. This is what we call runtime binding or dynamic binding.

So since there is dynamic binding, there must be static binding.

Dynamic binding calls a method at compile time, and it is the last method to be called at runtime, that is, to determine which method to call at run time.

Static binding means that you have determined which method to call during compilation.

Among them, the most prominent representative of dynamic binding is method rewriting.

The most prominent example of static binding is method overloading.

We are looking back at the above method ε = ('e.g.' *). How come the previous eat method returns the same value, parameter list, and method name? Let's take a look.

Method rewriting

We have learned about method overloading before. let's review method overloading. Method overloading means that the method name is the same, the return value is not required, and the parameter list is different. The method rewriting we learn today is that the return value is the same, the method name is the same, the parameter list is the same, it is called method rewriting can also be called method override.

There are several requirements for method rewriting:

The method rewrite satisfies that the method name is the same, the method's parameter list is the same, and the method's return value is the same.

We can also generate a rewrite with one click

There are several considerations:

Methods modified by private cannot be overridden.

Methods modified by final cannot be overridden.

The access to the method of the subclass must be greater than or equal to the access of the parent class.

The overridden method can be explicitly specified using the @ Override annotation. With this note, we can do some verification of legitimacy. For example, if you accidentally misspell the method name (such as eat), the compiler will find that there is no aet method in the parent class, and the compiler will report an error and prompt that it cannot be rewritten.

Methods modified by static cannot be overridden.

Summarize the considerations for method rewriting:

Methods modified by private,final cannot be overridden.

Methods modified by staitc cannot be overridden.

@ override can check whether the method name you rewrite is correct, preferably by adding it.

Method rewriting must satisfy that the method name is the same, the parameter list is the same, and the return value is the same.

Comparison method rewriting and method overloading:

Finally: rewriting is not a modification on the original basis, but an iteration and update on the original basis.

Further understanding and understanding of polymorphism

Scene: draw a graph

Class Shape {/ / create a graphics class-> the high public void draw () {System.out.println ("I want to draw a graph!") of the wide public int length;// graph of the long public int wide;// graph that is the parent of multiple graphics. ;} class rectangle extends Shape {/ / rectangle @ Override public void draw () {System.out.println ("I want to draw a rectangle!") ;} class square extends Shape {@ Override public void draw () {System.out.println ("I want to draw a square!") ;} class circular extends Shape {@ Override public void draw () {System.out.println ("I want to draw a circle!") ;} public class TestDemo1 {public static void method (Shape shape) {shape.draw ();} public static void main (String [] args) {Shape shape1 = new circular (); Shape shape2 = new rectangle (); Shape shape3 = new square (); method (shape1); method (shape2); method (shape3);}}

Create a Shape (parent class), and then create three subclasses, square and circular,rectangle, using the parent class to reference the three subclasses, and then call the method method.

This is polymorphism, different objects, call the same method and end up with different states.

Let's summarize the conditions for the generation of polymorphism:

Under the inheritance system

The subclass needs to override the methods of the parent class

Call the overridden method through a reference to the parent class

That is, upward transformation and method rewriting under the inheritance system.

The advantages of polymorphism

Advantages:

It can reduce the cyclomatic complexity of the code and avoid using a large number of if-else.

If you use polymorphism, you don't have to write so many if-else branching statements, and the code is simpler.

More scalable

Disadvantages:

The running efficiency of the code is reduced

Another important point is not to call the override method in the constructor.

At this point, the study of "Java object-oriented polymorphic case analysis" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report