• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

dengovo

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

多态

多态

Student

package com.oop.demo06;

public class Student extends Person{

    @Override
    public void run() {
        System.out.println("son");
    }

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

Person

package com.oop.demo06;

public class Person {
    public void run() {
        System.out.println("run");
    }
}

Application_06

package com.oop.demo_06;

import com.oop.demo06.Student;
import com.oop.demo06.Person;


public class Application_06 {
    public static void main(String[] args) {
        //一个对象的实际类型是确定的
        //new Student()
        //new Person()

        //可以指向的引用类型就不确定了:父类的引用指向子类

        //Student 能调用的方法都是自己的或者继承父类的
         Student s1 = new Student();
        //Person 父类型,可以指向子类,但是不能调用子类独有的方法
        Person s2 = new Student();
        Object s3 = new Student();

        s2.run();//子类重写父类的方法,执行子类的方法  son
        s1.run();//son

        //对象能执行哪些方法,主要看对象左边的类型,和右边的关系不大
        //s2.eat();
        ((Student) s2).eat();
        s1.eat();
    }
}

总结

多态注意事项:
  1. 多态是方法的多态,属性没有多态
  2. 父类和子类,有联系 类型转换异常!:ClassCastException!
  3. 存在条件:继承关系,方法需要重写,父类引用指向子类对象 Father f1 = new Son();

posted on 2022-07-24 16:21  邓了个邓  阅读(32)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3