Inherited Dark Horse programmer in Java

Source: Internet
Author: User

Code reuse is implemented through inheritance. All classes in Java are obtained by inheriting the Java.lang.Object class directly or indirectly. Inherited classes are called subclasses, and inherited classes are called parent classes. Subclasses cannot inherit member variables and methods in the parent class that have access rights private.
Subclasses can override the parent class's methods and name member variables with the same name as the parent class. However, Java does not support multiple inheritance, which is the ability of a class to derive from multiple classes of superclass.
classa{A () {}Private intx=10;//Private member variable of Class A (cannot be inherited)    protected inty=20;//protected member variables of Class A (can be inherited)    voidFun ()//Fun member method of Class A (can be inherited){System.out.println ("y+x=" + (y+x));//outputs two-digit and    } }classBextendsA//Class B is a subclass of Class A{B () {}voidGun ()//member methods for subclass B{y=y+1;//adds 1 to the value of the member variable y inherited from the parent class .System.out.println ("y=" +y); }} Public classTest2 { Public Static voidMain (String args[])//Main function{b b=NewB ();      B.gun ();      B.fun ();     B.gun (); }} Subclass B uses a fun method inherited from the parent class to manipulate the member variable x that is not inherited in the parent class and is allocated memory space ... Result of output: Y=21y+x=31y=22

Inherited Dark Horse programmer in Java

Related Article

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.