多态

多态:
子类重写父类方法
指向子类的父类引用该方法时,必定是调用子类中重写的方法
子类引用不能指向父类对象
多态有三个必要条件:继承、重写、向上转型
继承:必须存在子类与父类
重写:子类对父类中某些方法进行重新定义,在调用这些方法时就会调用子类的方法
向上转型:
格式为: 父类名 xxx = new 子类名;
或者 父类名 xxx;
xxx= new 子类名;
向下转型:与向上转型相反,即是把父类对象转为子类对象

举个例子:有2个类,Animal是父类,Cat类继承自Animal。

Animal an = new Cat(); // 这就叫 upcasting (向上转型)
// 现在an 引用指向一个Cat对象

Cat c1 = (Cat)an; // 这就叫 downcasting (向下转型)
// 现在an还是指向Cat对象

错误的向下转型:
父类名 A = new 父类名();
子类名 B = (子类名)A;//因为类型不一样所以要强制类型转换一下
A.方法;//方法为重写过后的方法

Animal类–>父类

  public class Animal {
	
	public void eat(){
		System.out.println("eat...");
	}

	public void sleep(){
		System.out.println("sleep...");
	}	
  }

Cat类–>子类

  public class Cat extends Animal{
    	
    	public void eat() {
    		
    		System.out.println("猫吃饭");
    		
    	}
    }

TestAnimal类–>测试类(解释向上转型和向下转型)

public class TestAnimal {
	public static void main(String[] args) {

		// 向上转型
		Animal an1 = new Cat();
		System.out.println("调用重写方法");
		an1.eat();
		System.out.println();// 换行
		
		System.out.println("调用父类中没有被重写的方法");
		an1.sleep();
		System.out.println();// 换行
		
		// 向下转型
		Cat an2 = (Cat) an1;
		an2.eat();
		System.out.println();
	}
}

在这里插入图片描述
TestError–>测试类(解释错误的向下转型)

public class TestError {
	public static void main(String[] args) {
		System.out.println("错误的向下转型");
		Animal an3 = new Animal();
		Cat an4 = (Cat) an3;
		an3.eat();
	}
}

在这里插入图片描述
方法的重写:(over reght)不在同一个类,同一个方法名,参数列表必须相同,覆盖重写。
方法重写(覆盖):
如果父类的方法不适合子类的话,子类可以进行方法的重写

  1. 前提子类继承了父类(继承且不是同一个类),如果父类满足不了子类的要求,子类可以对父类的方法进行重写
  2. 重写的规则:
    (1) 子类的方法名、参数列表、返回值类型必须和父类的一模一样。
    (2) 子类的重写方法的(访问)修饰符权限不能小于父类的访问修饰符。
    (3) 子类和父类,方法必须同为“static”或者非static
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值