Object-oriented features two 2.1: inheritance
① the introduction of class inherits fundamental role is: code reuse.
② grammar
[Modifiers List] class extends the parent class subclass name {name Body type; } |
③ After the subclass inherits the parent class, properties of the parent class declaration, a method, a subclass can be obtained.
Clear: when the parent class has private property or method, a subclass can also acquire obtained, but due to the design of the package, so that the call can not directly fills subclasses, but can be accessed indirectly. In addition the subclass through inheritance, obtaining the structure of the parent class, can also define their own unique component. Constructor can not be inherited by subclasses.
the extends : the subclass is a function of the parent class "extension" clearly a subset of the parent class is not a subclass.
Inheritance ④java class supports only single inheritance
A class can inherit from a parent class. On the contrary, a parent can have multiple children classes. If a class is not displayed inherit from other classes, the class inherits the default Object, Object is the root class of java SUN provided.
⑤ child-parent class is a relative concept
Customer does not show inherit from other classes, the default java.lang.Object extended SUN provided; there are all the Customer class toString method. public class Customer{ public static void main(String[] args){ Customer c = new Customer(); String s = c.toString(); System.out.println(s); //Customer@de6ced } }
|
example
/* Account class Parent class (superclass, the base class, the superclass) */ public class Account{ //account number private String actno; // Balance double balance; //Constructor Account(){} Account(String actno,double balance){ this.actno = actno; this.balance = balance; } //setter and getter public void setActno(String actno){ this.actno = actno; } public String getActno(){ return actno; } } |
/* Credit account Subclass (derived class, subclass) */ public class DebitAccount extends Account{ //Credibility double debit; } |
public class Test03{ public static void main(String[] args){ // Create an object credit card DebitAccount from DebitAccount = new (); // assign to the credit card account da.setActno ( "001"); // assignment // can be accessed indirectly. System.out.println (da.getActno ()); // read // there is no way to directly access //System.out.println(da.actno); } } |