什么是多态?
一种事务的多种形态
怎么使用多态? 多态的规则
1.使用多态的前提是 必须要有继承关系 类与类之间一定要有关系链接
2.必须要有重写方法 如果没有重写方法的话。 多态这种方法就没有什么意义了
3.父类的引用要指向 子类的对象
需求 创建 动物类 猫类 狗类 都有一个吃的方法 动物类吃 猫吃鱼 狗吃骨头
public class polymorphic{
public static void main(String [] agrs){
Animal a = new Cat();//猫是动物
a.eat();//方法的重写
Animalb = new Dog();//狗是动物
b.eat();//方法的重写
}
}
//创建一个父类 动物类
class Animal{
//创建一个成员方法 吃的方法
public void eat(){
System。out.println("吃东西");
}
}
//创建一个子类 猫类
class Cat{
public void eat(){ //写一个方猫吃鱼的方法
System.out.println("猫吃鱼");
}
}
//创建一个 狗类
class Dog {
public void eat(){
System.out。println("狗吃骨头");
}
}
多态时 成员变量如何调用?
比较下面两个例子
puvlid class ceshi {
public static void main (String[]agrs){
Father a = new Father();
a.speak();
System.out.println(a.say);
Son b = new Son();
b.speak();
System.out。println(a.say)
}
}
//创建一个父类
class Father {
int say = 10;
public void speak(){
System.out.println("Fathe说");
}
}
class Son{
int say = 1;
public void speak(){
System.out.println("Son 说")
}
}
新的例子
puvlid class ceshi {
public static void main (String[]agrs){
Father a = new Father();
a.speak();
System.out.println("a.say")
Son b = new Son();
}
}
//创建一个父类
class Father {
int say = 10;
public void speak(){
System.out.println("Fathe说");
}
}
class Son{
int say = 1;
public void speak(){
System.out.println("Son 说")
}
}
多态中父类引用时 调用成员变量
编译需要看父类中有没有成员变量 没有编译不会通过 系统会报错
运行时 访问的就是父类中的这个成员变量
所以说多态调用成员方法时
编译时看父类!
运行时看子类!
多态的好处?多态的弊端
需求 普通人 和骗子的故事
public class story {
public static void mian(String[]agrs){
People p = new Fraud();向上转型 父类引用子类对象
p.speak();
Fraud s= (Fraud)p; //强制转换
s.hit;
}
}
//父类
class People{
public void speak(){
System.out.println("聊天");
}
}
class Fraud extends People{
public void speak(){
System.out.println("洗脑")
}
public void hit(){
System.out.println("打你")
}
}
好处:1.增强了代码的可维护性 (建立在继承的基础上)
2.增强方法的可扩展性(核心)
弊端:不能调用子类的特殊方法(不是重写父类的方法)