java继承中的构造方法

1.子类的构造过程必须首先调用其基类的构造方法。

 

2.子类可以在自己的构造方法中使用super(argument_list)指定调用基类的构造方法,但必须写在子类方法的第一行。

 

3.同理可用this(argument_list)调用本类的另外构造方法。

 

4.如果没有显示的调用基类的构造方法,则系统默认系统默认调用基类无参数的构造方法。

 

5.如果子类的构造方法中没有显示调用基类的构造方法,基类也没有无参数的构造方法,则编译出错。

 

6.如果在类的修饰前是public, 则默认构造函数访问权限是  public ,如果 没有显示采用public修饰,则 默认构造函数的访问权限是 friendly。

 

Code:
  1. class Person {  
  2.     private String name;  
  3.     private String location;  
  4.     Person(String name) {  
  5.         this.name = name;  
  6.         location = "Beijing";  
  7.     }  
  8.     Person(String name, String location) {  
  9.         this.name = name;  
  10.         this.location = location;  
  11.     }  
  12.     public String info() {  
  13.         return "name: " + name + "  location: " + location;  
  14.     }  
  15. }  
  16.   
  17. class Student extends Person {  
  18.     private String school;  
  19.     Student(String n, String l, String school) {  
  20.         super(n, l);  
  21.         this.school = school;  
  22.     }  
  23.     Student(String name, String school) {  
  24.         this(name, "beijing", school);  
  25.     }  
  26.     public String info() {  
  27.         return super.info() + "  school: " + school;  
  28.     }  
  29. }  
  30.   
  31.   
  32.   
  33. public class Test {  
  34.     public static void main(String args[]) {  
  35.         Person p1 = new Person("A");  
  36.         Person p2 = new Person("B""shanghai");  
  37.         System.out.println(p1.info());  
  38.         System.out.println(p2.info());  
  39.           
  40.         Student s1 = new Student("C""S1");  
  41.         Student s2 = new Student("C","Shenyang","S2");  
  42.         System.out.println(s1.info());  
  43.         System.out.println(s2.info());    
  44.     }  
  45. }  

输出结果:

Code:
  1. /* 
  2. name: A  location: Beijing 
  3. name: B  location: shanghai 
  4. name: C  location: beijing  school: S1 
  5. name: C  location: Shenyang  school: S2 
  6. */  

 

你可能感兴趣的:(java,c,list)