对于面向对象的编程,最总要的三个特征就是继承、封装、多态。我们现在来看看继承是如何一步一步实现的。看下面代码:
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()在引用构造函数时必须放在第一行,引用非构造函数无此要求。
Java继承构造函数解析
本文通过具体示例详细解析了Java面向对象编程中继承的概念,包括构造函数的调用顺序、this关键字和super关键字的使用方法及其作用。
422

被折叠的 条评论
为什么被折叠?



