Inherit the dark horse programmer in java and the dark horse in java

Source: Internet
Author: User

Inherit the dark horse programmer in java and the dark horse in java

Implement code reuse through inheritance. All classes in Java are obtained by directly or indirectly inheriting the java. lang. Object Class. The inherited class is called a subclass, And the inherited class is called a parent class. Subclass cannot inherit the member variables and methods whose access permission is private in the parent class.
Subclass can override the parent class method and name the member variables with the same name as the parent class. However, Java does not support multi-inheritance, that is, the ability of a class to derive from multiple superclasses.
Class A {A () {} private int x = 10; // The private member variable of class A (which cannot be inherited) protected int y = 20; // protection member variable of Class A (can be inherited) void fun () // fun member method of Class A (can be inherited) {System. out. println ("y + x =" + (y + x )); // output two numbers and} class B extends A // class B is A subclass of class A {B () {} void gun () // member method {y = y + 1 of subclass B; // Add the value of member variable y inherited from the parent class to 1 System. out. println ("y =" + y) ;}} public class test2 {public static void main (String args []) // main function {B B B = new B (); b. gun (); B. fun (); B. gun () ;}} subclass B The fun method inherited by the parent class operates the member variable X that is not inherited and is allocated memory space in the parent class ...... Output result: y = 21y + x = 31y = 22

 

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.