Differences between member variables and member functions during JAVA Relay

Source: Internet
Author: User

 Class first:
 

 package ExtendsTest;public class First { int a=1; public void print() {  System.out.println(a); }}

The second type is as follows:

 package ExtendsTest;public class Second extends First{ int a=2; int b=3; public void print() {  System.out.println(a); }}

 

Run the following code:

package ExtendsTest;public class Test { public static void main(String []args) {  First c1=new Second();      System.out.println(c1.a);  c1.print();  Second c2=new Second();  System.out.println(c2.a);  c2.print(); }}

The output result is 1 2 2 2.

Focus on system. Out. println (c1.a );
     C1.print ();

Why are the output results 1 and 2.

Because in the Inheritance Mechanism of Java, if the object of the subclass is accessed by reference of the parent class.
For the member variables redefined by the quilt class, the parent class accesses its own member variables.

That is to say, the member variables are accessed Based on the referenced type.

The methods are different. If the parent class references a method that calls a quilt class override, the method accessed is the sub-class.

Class method.
This seems to be called dynamic binding.

That is to say, the member method is accessed Based on the object type.

Summary:
Methods and variables for quilt class rewriting. The preceding a variable and print () method.

When accessing with the parent class reference (first C1) pointing to the subclass object (new second.
Its member variables. The parent class accesses the member variables of the parent class.
Its member method. The parent class accesses the member method of the subclass.

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.