您的位置:首页 > 编程语言 > Java开发

java继承中的构造方法

2011-03-26 21:25 344 查看
1.子类的构造过程必须首先调用其基类的构造方法。

 

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

 

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

 

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

 

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

 

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

 

Code:

class Person {  

    private String name;  

    private String location;  

    Person(String name) {  

        this.name = name;  

        location = "Beijing";  

    }  

    Person(String name, String location) {  

        this.name = name;  

        this.location = location;  

    }  

    public String info() {  

        return "name: " + name + "  location: " + location;  

    }  

}  

  

class Student extends Person {  

    private String school;  

    Student(String n, String l, String school) {  

        super(n, l);  

        this.school = school;  

    }  

    Student(String name, String school) {  

        this(name, "beijing", school);  

    }  

    public String info() {  

        return super.info() + "  school: " + school;  

    }  

}  

  

  

  

public class Test {  

    public static void main(String args[]) {  

        Person p1 = new Person("A");  

        Person p2 = new Person("B", "shanghai");  

        System.out.println(p1.info());  

        System.out.println(p2.info());  

          

        Student s1 = new Student("C", "S1");  

        Student s2 = new Student("C","Shenyang","S2");  

        System.out.println(s1.info());  

        System.out.println(s2.info());    

    }  

}  

输出结果:

Code:

/* 

name: A  location: Beijing 

name: B  location: shanghai 

name: C  location: beijing  school: S1 

name: C  location: Shenyang  school: S2 

*/  

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java list c