多态:面对对象语言的特征之一 可以精简代码 // 多态 必须发生运行时绑定 /*1、只是通过一个animal.eat(); * 2、传递的参数不一样 代表这个引用引用的对象不一样 * 3、通过这个引用调用同一个方法,表现出了不同的形式。这种思想,这种情况,叫做多态 * */
class Animal {
public String name;
public int age;
public void eat() {
System.out.println(name + " eat()");
}
public Animal(String name,int age){
this.name = name;
this.age = age;
eat();//构造方法 调用重写 、、坑、、
}
}
class Dog extends Animal{//Java中只能通过extends继承一个类,不能继承多个类
//子类对象要构造 先帮父类对象进行构造 所有的构造对象都得通过构造方法构造
public Dog(String name,int age){
super(name,age);
}
public void eat() {//重写
System.out.println("Dog::eat()");
}
}
class Bird extends Animal{
public String selfFired;
public Bird(String name,int age,String selfFired ){
super(name, age);//只能放在最前边
this.selfFired = selfFired;
}
public void fly(){
System.out.println(name+"fly()");
}
public void eat() {//重写 父类中有 会发生运行是绑定
System.out.println("Bird::eat()");
}
}
public class TestDemo {
/**
*构造方法 调用重写
* @param
* */
public static void main(String[] args) {
Dog dog = new Dog("lilli",3);//Dog::eat()
//此时构造方法 调用重写 所以打印的还是 调用重写 而不是lilli eat()
}
// 多态 必须发生运行时绑定
/*1、只是通过一个animal.eat();
* 2、传递的参数不一样 代表这个引用引用的对象不一样
* 3、通过这个引用调用同一个方法,表现出了不同的形式。这种思想,这种情况,叫做多态
* */
public static void func(Animal animal) {
animal.eat();// 调用的eat方法 Dog与Bird进行了重写 才能构成多态
}
public static void main5(String[] args) {
Dog dog = new Dog("lilli",3);
func(dog);
Bird bird = new Bird("keke",5,"susu");
func(bird);
}
// 多态
例如
打印微笑和菱形
class Shape{
public void draw(){
}
}
class Cycle extends Shape{
@Override
public void draw() {
super.draw();
System.out.println("😊");
}
}
class Rect extends Shape{
@Override
public void draw() {
super.draw();
System.out.println("♦");
}
}
public class TestExample {
//调用多态 shape.draw();
public static void drawShapes(){
//创建一个Shape 对象数组
Shape[] shapes = {new Cycle(),new Rect(),new Cycle(),new Rect()};
new Rect();
for (Shape shape : shapes){
shape.draw();
}
}
public static void drawMap(Shape shape) {
shape.draw();
}
//运用循环打印 cycle.draw();/rect.draw();
public static void drawMap1() {
Rect rect = new Rect();
Cycle cycle = new Cycle();
String[] shapes = {"1","2","1","2"};
for (String shape : shapes){
if (shape.equals("1")){
cycle.draw();
}else if (shape.equals("2")){
rect.draw();
}
}
}
public static void main(String[] args) {
Cycle cycle = new Cycle();
Rect rect = new Rect();
drawMap(cycle);
drawMap(rect);
drawShapes();
}
}
结果
😊
♦
😊
♦
😊
♦
Process finished with exit code 0