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

JAVA学习(10) 继承(3) 继承中的构造函数

2016-05-27 16:56 501 查看
父类:

public class Obj {
public  Obj()
{
System.out.println("Obj构造");
}

public  Obj(String s)
{
System.out.println("Obj构造"+s);
}
}


子类会调用父类的无参数构造函数

public class Test11A extends Obj {

public static void main(String[] args) {
// TODO 自动生成的方法存根
Test11A test11a = new Test11A();
System.out.println("hello");

}

}


子类会调用父类的无参数构造函数 然后再调用自身的构造函数

public class Test11A extends Obj {
public Test11A()
{
System.out.println("Test11构造");
}

public static void main(String[] args) {
// TODO 自动生成的方法存根
Test11A test11a = new Test11A();
System.out.println("hello");

}

}


子类会调用父类的无参数构造函数 然后再调用自身的有参数构造函数

public class Test11A extends Obj {
public Test11A()
{
System.out.println("Test11构造");
}

public Test11A(String s)
{

System.out.println("Test11构造"+s);
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
Test11A test11a = new Test11A("hello");
System.out.println("hello");

}

}


super关键字返回父类的引用,可以使用引用强制设置调用父类的有参数构造函数

public class Test11A extends Obj {
public Test11A()
{
System.out.println("Test11构造");
}

public Test11A(String s)
{
super(s);
System.out.println("Test11构造"+s);
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
Test11A test11a = new Test11A("hello");
System.out.println("hello");

}

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