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

【奔跑的菜鸟】Java中的继承关系

2016-07-14 15:49 555 查看
对于面向对象的编程,最总要的三个特征就是继承、封装、多态。我们现在来看看继承是如何一步一步实现的。看下面代码:
public class Test
{
public static void main(String[] args)
{
FuncationOfThis m_this = new FuncationOfThis();
System.out.println("*******************************************");
Child m_child = new Child();
System.out.println("*******************************************");
Child m_childargs = new Child(1);
}
}

class FuncationOfThis
{
FuncationOfThis()
{
this(1);
System.out.println("with_this");
}
FuncationOfThis(int i)
{
System.out.println("without_this");
}

}

class Parent
{
Parent()
{
System.out.println("parent");
}

Parent(int i)
{
System.out.println("argsParent"+i);
}
}

class Child extends Parent
{
Child()
{
System.out.println("child");
}

Child(int a)
{
super(a);
System.out.println("argsChild"+a);
}

}

运行结果如下:

without_this
with_this
*******************************************
parent
child
*******************************************
argsParent1
argsChild1

先是this()的用法,this()是调用这个类带参数的构造函数。而super()是调用父类带参数的构造函数。this()和super()在构造函数中使用时必须出现在构造函数的第一行。关于构造函数的调用顺序,在new一个新对象是调用构造函数。如果new的对象有父类,那么先调用父类的构造函数,再调用子类的构造函数。

this()表示对自身类的引用,super()表示对父类的引用。super()在引用构造函数时必须放在第一行,引用非构造函数无此要求。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息