Modifier of the polymorphism Method

Source: Internet
Author: User

Warming-up, Basic Concepts

A ---- references and objects

Now there is a parent class father, which derives from a subclass son

In the statement Father = new son,

Father is just a reference, and the real object refers to the new son () instance.

We often say that static binding and dynamic binding are determined by reference during compilation, while dynamic binding is determined by objects during runtime. The relationship is as follows:

Static binding --> during compilation --> reference

Dynamic binding --> runtime --> Object

B ----- about rewriting

Polymorphism is based on method rewriting, that is, if the method of the parent class is of the private type, there is no rewrite (because the subclass does not see this private method of the parent class, what can be said ,,, heavy !!! Write)

Bytes --------------------------------------------------------------------------------------------

I. polymorphism of attributes

Sorry, this is not within the title scope, but I want to discuss the attributes as well. Hey, I have to apologize again. The title deceives everyone. In fact, there is no polymorphism in the attributes. The attribute used depends entirely on the compilation stage, that is, the reference determines.

For example, in the following program, the parent class and subclass have attributes of the same name.

class Cat{public int age = 10;}class WhiteCat extends Cat{public int age = 100;}public class Test {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubCat cat = new WhiteCat();System.out.println(cat.age);WhiteCat whitecat = new WhiteCat();System.out.println(whitecat.age);}}


The output is

10
100
If the property page of the method has polymorphism, the first output here should be 10. However, this is not the case. As mentioned above, the property call is static binding, that is, it is determined during the compilation period, that is, through the reference decision (static-during the compilation period --- reference, haha, this can almost become a mantra ). Therefore, it is easy to see that the first output is 10, and the reason for the second output is as follows:

If a subclass parent class has an attribute with the same name, the attributes of the parent class will be hidden in the subclass. In fact, even if the data type of the parent class and the attributes with the same name are different, it also produces the same hidden effect, and even if both attributes are declared as final, there will be no errors (in method rewriting, you will find that, final-type methods cannot be overwritten), So !! You should understand the second output.

In addition, attributes are generally set to private, and attributes of the same name are not set between parent classes to prevent confusion.

Bytes --------------------------------------------------------------------------------------------

2. modifier OF THE METHOD

A, final method Rewriting

class D0{        public final void f1(){System.out.println("D0  F1");}}class D1 extends D0{       @Override       public void f1(){}}

After you break the above Code into the compiler, you will find that the compilation fails.

Error: cannot override the final method from D0

That is to say, the final method cannot be rewritten.

Will someone be curious, adding final to the F1 method in the D1 class, will it not report an error?

The truth is ,,,,

The compilation still fails. The reported error is still cannot override the final method from D0.

Then, let's make another small experiment. If the @ override clause is removed, there is still a bug. The Compiler thinks that you are still rewriting it. As for the reason, leave it for later explanation.

B. Rewrite the private Method

B1,

First, let's look at the first situation

class D0{private void f2(){System.out.println("D0  F2");}}class D1 extends D0{@Overridepublic void f2(){System.out.println("D1 F2");}}

You will find that the OMG program cannot be compiled properly, and the compile-error shown is

The method F2 () of Type D1 must override or implement a supertype Method

What does supertype mean? What does it mean in Chinese? n. supertype; parent type

That is to say, we can only override some super-type methods (such as protected, public, and friend in the same package), while private is not super-type.

B2,

Let's look at another small example below.

class D0{private void f2(){System.out.println("D0  F2");}}class D1 extends D0{public void f2(){System.out.println("D1 F2");}}

Why? Isn't this code the same as the previous one? It seems like the truth. Let's take a look at it again. There is a missing override.

At this time, the compilation is successful! Next, let's write a small test program and try it out.

public static void main(String[] args) {// TODO Auto-generated method stubD0 obj1 = new D0();obj1.f2();D0 obj2 = new D1();obj2.f2();}

At this time, compilation failed again and there were two errors.

First, in obj1.f2 (0, the error "T" and "T" cannot be seen. How can I use an instance to directly access the private method?

Second, in obj2.f2 (), the error message displayed is:

The method F2 () from the type D0 is not visible

At this time, if there is no rewrite, it will not wait until the running phase is bound dynamically, but it will be bound in the compilation phase, and the compilation phase is bound by reference, in this case, the obj2 reference belongs to the D0 type. In the D0 type, the F2 () method is private and cannot be accessed.

B3, a small difference between the private method and the final Method

Let's take a look at the following code.

class A{public final void f1(){}private void f2(){}}class B extends A{private void f3(){super.f2();super.f1();}}

Is it a simple example? Hahaha.

The Methods declared by private and final have one thing in common, that is, they cannot be overwritten by the quilt class, but cannot be overwritten for another reason,

Private is because it cannot be seen in the subclass (as can be seen from the code above). Therefore, in the subclass, write a method that is the same as the private method in the parent class, it is actually a new method.

As for final, although the subclass cannot be rewritten, the special point is that the subclass can see it. Therefore, if you want to write the same method in the subclass, even if there is no annotation @ override, as you can see it, the compiler will rewrite it if you think it is a good idea. So of course an error is reported.


C. Static Method Rewriting

Let's talk about two terms.

Static method indicates a static method, that is, a class method.

Instance method is an instance method, that is, an object method.

C1Static Method override static method

Let's look at the following small example.

Class cat {public static void F1 () {system. out. println ("cat F1");} class whitecat extends cat {// @ overridepublic static void F1 () {system. out. println ("whitecat F1") ;}} public class test {/*** @ Param ARGs */public static void main (string [] ARGs) {// todo auto-generated method stubcat cat = new whitecat (); cat. f1 (); whitecat wcat = new whitecat (); wcat. f1 () ;}} output: CAT f1whitecat F1

You may have discovered that the polymorphism is not shown here,

Let's first discuss the first output.

First, the call to the static method is determined during compilation. Therefore, it is determined by reference.

That is

Cat cat = new WhiteCat();cat.f1();

In the two statements, cat is a reference of the cat type. Therefore, the F1 method in the cat class is called naturally.

Next we will discuss the second output.

When the F1 method is not rewritten in the whitecat class,

The second output should be

Cat f1

Because the F1 () method is public, it is inherited.

However, at this time, in the subclass whitecat, We have rewritten the F1 () method. What will happen at this time ???. That is, in the subclass, the F1 () method inherited by the parent class is hidden by the new F1 () method,

There is an article about the differences between rewriting and hiding. You can see the differences between rewriting and hiding in polymorphism later.

Therefore, this is the reason for the second output.

,,,,,

Strictly speaking, static methods cannot be overwritten by static methods.

If you remove the above @ override gaze from the F1 () method of the subclass above

An error is reported during compilation. The error is as follows:

The method F1 () of Type whitecat must override or implement a supertype Method

It seems that the static method is not a supertype method either.

Next, let's talk about another situation ,,,

C2The static method overwrites the instance method, and the instance method overwrites the static method.

class Cat{public static void f1(){System.out.println("Cat f1");}public void f2(){System.out.println("Cat f2");}}class WhiteCat extends Cat{public void f1(){System.out.println("WhiteCat f1");}public static void f2(){System.out.println("WhiteCat f1");}}


Soon, you will find that the compilation fails

The following error is reported near the F1 () method of the subclass:

This instance method cannot override the static method from cat

The following error is reported near the F2 () method of the subclass:

This static method cannot hide the instance method from cat

Do not overwrite the other side with static methods and instance methods.

Synthesis of static methods in Polymorphism

Static methods cannot overwrite the instance method or the instance method.

Static methods cannot overwrite static methods, but can only overwrite static methods in the parent class,

In addition, static methods are called through objects, that is, they are determined during the compilation period and belong to static binding.

Now, let's look at every example. In fact, static methods cannot achieve polymorphism at all.

Finally, when a method is rewritten, the access permission of the subclass method must at least be equal to that of the parent method.

It is often confusing.

The following is an online blog on polymorphism.

Deep understanding of Java Polymorphism


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.