Java---接口、继承与多态

目录

 

一、类的继承

二、Object类

1. getclass()方法

2. toString()方法

3. equals()方法

三、对象类型的转换

四、使用instanceof操作符判断对象类型

五、方法的重载

定义不定长参数方法

六、多态

七、抽象类与接口

1、抽象类

2. 接口

3. 接口与继承


一、类的继承

在subroutine.java中:

class Parent{
	Parent(){
		System.out.println("调用父类的Parent()构造方法");
	}
}

class SubParent extends Parent{
	SubParent(){
		System.out.println("调用子类的subParent()构造方法");
	}
}

public class subroutine extends SubParent {
	subroutine(){
		System.out.println("调用子类的subroutine()构造方法");
	}
	public static void main(String[] args) {
		subroutine obj = new subroutine();
	}
}

运行结果为:

在实例化子类对象时,父类无参构造方法将被自动调用,但又参构造方法不能被自动调用。只能依赖于super关键字显式调用父类的构造方法。创建一个子类对象,将包含一个父类子对象。当实例化子类对象时,父类对象也相应被实例化。


(以下具体代码)

class text{
	text(){
		System.out.println("call the constructor of text()");
	}
	public void doSomething() {
		System.out.println("doSomething");
	}
	protected text dolt() {
		return new text();
	}
}
public class text2 extends text{
	text2(){
		super();
		System.out.println("call the constructor of text2()");
	}
	public void doSomething() {
		System.out.println("doSomething in class text2");
	}
	public void doNew() {
		System.out.println("doNew here");
	}
	protected text2 dolt() {
		return new text2();
	}
	
	public static void main(String[] args) {
		text2 obj = new text2();
		obj.doSomething();  //执行text2类中的方法
		obj.doNew();
		obj.dolt();   //执行text2类中的方法
	}

}

结果为:

call the constructor of text() 创建父类对象
call the constructor of text2() 创建子类对象
doSomething in class text2 调用text2中的重写方法
doNew here 调用text2中新添加的方法
call the constructor of text() 调用text2中的dolt()方法,创建对象,先创建一个父类对象
call the constructor of text2() 再创建一个子类对象

1. super关键字:

可以在子类的构造方法中调用super()语句调用父类的构造方法;也可以在子类中使用super关键字调用父类的成员方法(仅public、protected)。

2. 重写(覆盖)父类的成员方法:

将父类成员方法的名称保留,                  

1)重写成员方法的实现内容  
2)更改成员方法的存储权限: 只能从小范围改到大范围
3)修改成员方法的返回类型: 遵循:重写的返回值类型必须是父类该方法的返回值类型的子类

重写方法的调用:

   
1)用实例化对象是调用不到父类的 在内存中仍为子类对象  
2)只能用super关键字

1)且只能在类方法中调用

2)在main(类外部)是调用不到的

 
  (最初overrride的设计意图之一)  
class Father{
	
  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值