Java Review of inheritance

Source: Internet
Author: User

Inherited

Extends is the meaning of expansion, not inheritance. That is, the child class is the extension of the parent class, which is a special kind of parent class. (subclasses cannot inherit constructors)

Inherit from parent class such as

Class fruit{Public String name, public void info () {System.out.println ("name" +name+ "Delicious");}} Class Apple extends Fruit{public static void main (string[] args) {Apple apple=new apple (); apple.name= "Apple"; Apple.info ( );}}

Very well understood.

Overriding the parent class method

Class Banana extends fruit{
public void info () {System.out.println ("name" +name+ "not Tasty");}}
It's called bananas, not tasty.

This is not the parent's info method, that is, the subclass overrides the method of the parent class, also called the method override override

Overriding method follows "two and two small one big"

Two-way: Method name, formal parameter list

Two small: The return value is smaller or equal than the return value type of the parent class, the exception specification is small or equal

A large: The access rights of subclasses are larger or equal than the parent class

After a subclass is overridden, you cannot access methods that are hidden by the parent class, but you can use the "super" keyword or use the "parent class name" to invoke the hidden method.

Class Banana extends fruit{public void info () {System.out.println ("name" +name+ "not Tasty");} public void Callsuper () {super.info ();} public static void Main (string[] args) {banana b=new banana (); b.name= "Banana"; B.info ();   B.callsuper ();}} The name is Banana Delicious

  

If the parent class method is private, it is not called an override, which is called a new method

Java Review of inheritance

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.