一、语法机制:
1.Anima、Cat、Bird三个类之间的关系: Cat继承Animal Bird继承Animal Cat和Bird之间没有任何继承关系 2.面向对象的三大特征:封装,继承,多态。 3.关于多态的概念:
- 向上转型(upcasting)
子类型—>父类型 又被称为:自动类型转换 - 向下转型(downcasting)
父类型—>子类型 又称为强制类型转换。【需要加强制类型转换符】 需要记忆:无论是向下转型还是向上转型,两者之间都必须要有继承关系。 没有继承关系,程序是无法编译运行通过的。
package test001;
import sun.print.PrintJob2D;
public class Test {
public static void main(String[] args) {
Animal a1 = new Animal();
a1.move();
Cat c1= new Cat();
c1.move();
c1.catchMouse();
Bird b1 = new Bird();
b1.move();
Animal a2=new Cat();
a2.move();
Cat c2=(Cat)a2;
c2.catchMouse();
Animal a3 = new Bird();
Cat a3=(Cat)a3;
if(a3 instanceof Cat) {
Cat c3=(Cat)a3;
c3.catchMouse();
}
else if(a3 instanceof Bird) {
Bird b2 = (Bird)a3;
b2.fly();
}
}
}
package test001;
public class Bird extends Animal {
@Override
public void move() {
System.out.println("鸟儿在飞翔");
}
public void fly() {
System.out.println("鸟儿在飞翔");
}
}
package test001;
public class Cat extends Animal {
@Override
public void move() {
System.out.println("猫在走猫步");
}
public void catchMouse() {
System.out.println("猫可以抓老鼠");
}
}
package test001;
public class Animal {
public void move() {
System.out.println("动物在移动");
}
}
二、多态在实际开发中的作用:
package test002;
public class Test {
public static void main(String[] args) {
Master master=new Master();
master.feed(new Cat());
master.feed(new Dog());
Snake mangshi=new Snake();
master.feed(mangshi);
}
}
package test002;
public class Pet {
public void eat() {
}
}
package test002;
public class Master {
public void feed(Pet pet) {
pet.eat();
}
}
package test002;
public class Cat extends Pet {
public void eat() {
System.out.println("小猫在吃鱼");
}
}
package test002;
public class Dog extends Pet {
public void eat() {
System.out.println("小狗正在啃骨头");
}
}
package test002;
public class Snake extends Pet {
public void eat() {
System.out.println("蛇吞象");
}
}
|