前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java 类的封装、继承、多态

Java 类的封装、继承、多态

作者头像
Michael阿明
发布2021-09-06 10:01:14
6950
发布2021-09-06 10:01:14
举报
文章被收录于专栏:Michael阿明学习之路
代码语言:javascript
复制
// 封装、继承、多态
class Person1{
    String name;
    int age;
    private int height;// 私有 封装
    public Person1(String name, int age)
    {
        this.name = name;
        this.age = age;
    }
    public void talk()
    {
        System.out.println("This is father class talk() !");
    }
    public void setHeight(int h)
    {
        if(h > 0)
            this.height = h;
    }
    public int getHeight()
    {
        return this.height;
    }
}

// 继承(只能继承单个父类) extends father_class
class Student extends Person1{ // java 一个子类只能有一个父类
    String school;
    public Student(String name, int age, String school)
    {
        super(name,age);//调用父类的构造方法,且必须放在第一行
        this.school = school;

        // super. 调用父类属性、方法
        super.name = "Ming";
        super.age = 19;

        // 私有属性不可修改
        // super.height = 178;
        super.setHeight(178);
    }

    @Override
    public void talk() { // 重写父类方法
        System.out.println("This is sub class talk() !");
        super.talk();//还可以调用父类被覆写的方法
    }
}

class test1{
    public static void main(String[] args){
        Student s1 = new Student("Michael",18,"BJTU");
        System.out.println("name: "+s1.name+", age: "+s1.age+
                ", school: "+s1.school + ", height: " + s1.getHeight());

        s1.talk();

        Person1 p = new Student("Ming",19,"BJTU");
        p.talk();// 多态,父类对象通过子类实例化,调用的是子类的talk

        Student s2 = (Student) p;//向下类型转换,需要强制,向上是自动转的
        s2.talk();// 如果 p 是由 Person1 new 出来的,此处报错
    }
}

输出:

代码语言:javascript
复制
name: Ming, age: 19, school: BJTU, height: 178
This is sub class talk() !
This is father class talk() !
This is sub class talk() !
This is father class talk() !
This is sub class talk() !
This is father class talk() !

进程已结束,退出代码0
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/02/25 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档