Inheritance of three major features of Java

Source: Internet
Author: User

The inheritance of objects is accomplished through extends in Java

The code is as follows:

Package Hello;class person{private string name;private int age;public string getName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;}} Class Student extends Person{public void Tell () {System.out.println (GetName () + "+ Getage ())}} public class Extendsdemo {public static void main (string[] args) {Student Student = new Student (); student.setage; stude Nt.setname ("Zhangsan"); Student.tell ();}}

We pass

Class Student extends Person

To complete the Student object's inheritance of the person object, which in Student can access the properties and methods in the parent class, and, of course, in the example above, the private attribute (name and age) in the parent class is encapsulated by private and therefore requires the getName and Getage to complete its visit.

Two restrictions on inheritance:

1. You can inherit only one object in Java (multiple objects can be inherited in Python)

2. Subclasses cannot directly access private properties in the parent class

About the instantiation process of a subclass object

Before a subclass object is instantiated, the constructor method in the parent class must be called before the child class is called. The code is as follows:

Package Hello;class Father{public Father () {System.out.println ("constructor method for parent class");}} Class Son extends Father{public son () {System.out.println ("constructor method of the subclass");}} public class Extendsdemo {public static void main (string[] args) {son son = new Son ();}}

Program output:

How to construct a child class of a parent class

 

Inheritance of three major features of Java

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.