The inheritance of Java

Source: Internet
Author: User

In Java inheritance, subclasses are also referred to as derived classes, and the parent class is also called a base class or superclass, the basic syntax: Subclass extends parent class {}

To implement a simple inheritance class:

classperson{PrivateString name; Private intAge ;  Public voidsetName (String name) { This. Name =name; }     PublicString GetName () {returnname; }     Public voidSetage (intAge ) {         This. Age =Age ; }     Public intGetage () {returnAge ; }}classStudentextendsperson{PrivateString School;  Public voidSetschool (String school) { This. School =School; }     PublicString Getschool () {returnSchool; }} Public classtest{ Public Static voidMain (String args[]) {Student stu=NewStudent (); Stu.setname ("Pupils");//Parent class MethodStu.setage (18);//Parent class MethodStu.setschool ("Blue Cheung Excavator Specialized college");//own MethodSystem.out.println (Stu.getname () + "," + stu.getage () + "," +Stu.getschool ()); }}

When instantiating a subclass, first executes the parent constructor and then executes the subclass

classperson{ PublicPerson () {System.out.println ("Parent class no parameter constructs"); }}classStudentextendsperson{ PublicStudent () {Super();//super () is not written here; it is also called by defaultSYSTEM.OUT.PRINTLN ("Subclass non-parametric construction"); }} Public classtest{ Public Static voidMain (String args[]) {NewStudent ();//by default, the parent class is called without a parameter construct    }}/*Execution Result: parent class no parameter construction subclass no parameter construction*/
classperson{PrivateString name;  PublicPerson (String name) {System.out.println ("Parent class no parameter construction" +name); }}classStudentextendsperson{ PublicStudent () {Super("Java");//call the parent class with a parameter construct, be sure to put it in the first statement, and this () is similarSYSTEM.OUT.PRINTLN ("Subclass non-parametric construction"); }} Public classtest{ Public Static voidMain (String args[]) {NewStudent ();//by default, the parent class is called without a parameter construct    }}/*Execution Result: parent class no parameter construction subclass no parameter construction*/

The sub-class notes in the method of the parent class override

Which class is instantiated, when the instantiated object calls the method of the class by default, and if the method is not present in the child class, the method in the parent class is called.

When a subclass is covering a method in a parent class, the method's access permission cannot be higher than the parent class, and if the parent defines a method with private, the subclass cannot overwrite it, because the private defined method can only be used in this class, even if the subclass writes the same method. Nor can it be called overwrite

classa{ Public voidprint () {System.out.println ("Methods in Class A"); }     Public voidFun () {System.out.println ("Class B did not overwrite the method, calling the parent class by default"); }}classBextendsa{ Public voidprint () {System.out.println ("Methods in Class B"); }} Public classtest{ Public Static voidMain (String args[]) {b b=NewB ();    B.print (); //methods in class BB.fun ();//Class B does not overwrite the method, the parent class is called by default    }}

This. Method (): First, the child class is found whether the method exists, if there is a direct call, if it does not exist, look for the method in the parent class, if there is a direct call, if not there is a compilation error;

Super. Method (): Call the method in the parent class directly, or compile-time error if it does not exist;

The difference between overloading and overriding:

Overloading (overloading): In a class, the method name is the same, the number of parameters and the type is different; The method defines no permission restrictions;

Overwrite (Overrid): Occurs in the inheritance relationship, the method name is the same, the number of parameters and the same type, the return value is the same, the subclass can not be more strict than the parent class;

A case of inheritance that does not require attention

classarray{Private intdata[]; Private intFoot;  PublicArray (intLen) {        if(Len! = 0){             This. data =New int[Len]; }Else{             This. data =New int[1]; }    }     Public voidAddintnum) {        if( This. foot>= This. Data.length) {            return; }Else{             This. data[foot++] =num; }    }     Public int[] GetData () {return  This. Data; }}//define a sort classclassSortarrayextendsarray{ PublicSortarray (intLen) {        Super(LEN);//explicit invocation of the parent class of a parameterized construct that is initialized for an array    }    //overwrite the parent class method     Public int[] GetData () {Java.util.Arrays.sort (Super. GetData ());//        return Super. GetData (); }}//invert an arrayclassReversearrayextendsarray{ PublicReversearray (intLen) {        Super(len); }     Public int[] GetData () {intnum =Super. GetData (). Length/2;//Number of reversals        intHead = 0; intTail =Super. GetData (). length-1;  for(intx = 0;x < num;x++){            inttemp =Super. GetData () [head]; Super. GetData () [head] =Super. GetData () [tail]; Super. GetData () [Tail] =temp; Head++; Tail--; }        return Super. GetData (); }} Public classtest{ Public Static voidMain (String args[]) {Reversearray arr=NewReversearray (3); Arr.add (1); Arr.add (10); Arr.add (3); Arr.add (4); //Arr.add (5);        intData[] =Arr.getdata ();  for(intx=0;x<data.length;x++) {System.out.print (data[x]+ "\ T"); }    }}

The inheritance 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.