About Java subclasses calling parent class methods

Source: Internet
Author: User

When a class inherits from another class, the subclass does not have a method of the parent class. When you invoke a method with an object of a subclass, it is first found in the subclass, and if there are no changes in the subclass, look in the parent class.

When a method is defined only in the parent class, the property in the parent class is used when the method is called.
If another method is called in the method, then it will be found in the subclass in the previous order, and then in the parent class.

 PackageTemp;classA {intx = 6; Private inty = 2;  PublicAinta) {x=A; }    intGetz () {intZ; Z= x/y; returnZ; }    voidShow () {System.out.println ("X=" +x); System.out.println ("Y=" +y); System.out.println ("Z=" +Getz ()); }}classBextendsA {intx = 3, y = 5, Z;  PublicBinta) {Super(a); }    intGetz () {Z= x +y; returnZ; }} Public classTemp { Public Static voidMain (string[] args) {A num1=NewA (10); B num2=NewB (9);        Num1.show ();    Num2.show (); }}

The result is:

x=10y=2z=5x=9y=2z=8

About Java subclasses calling parent class methods

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.