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

对于面向对象的编程,最总要的三个特征就是继承、封装、多态。我们现在来看看继承是如何一步一步实现的。看下面代码:
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()在引用构造函数时必须放在第一行,引用非构造函数无此要求。


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值