Java的封装、继承与多态

封装

封装(Encapsulation)是面向对象方法的重要原则,就是把对象的属性和操作(或服务)结合为一个独立的整体,并尽可能隐藏对象的内部实现细节。

publicclassStudent{//封装//属性私有privateString name;privateString id;privateString sex;//通过get、set方法操作数据//get 获取数据publicStringgetName(){returnname;    }publicStringgetId(){returnid;    }publicStringgetSex(){returnsex;    }//给数据赋值publicvoidsetName(String name){this.name = name;    }publicvoidsetId(String id){this.id = id;    }publicvoidsetSex(String sex){this.sex = sex;    }}

继承

继承是从已有的类中派生出新的类,新的类能吸收已有类的数据属性和行为,并能扩展新的能力。

Person父类

publicclassPerson{publicinta=1;publicvoidtalk(){        System.out.println("Person");    }}

Student子类

publicclassStudentextendsPerson{publicvoidsay(){        System.out.println("Student");    }}

测试用例

publicclassApplication{publicstaticvoidmain(String[] args){        Student student=newStudent();        System.out.println(student.a);//继承父类的成员变量student.say();//子类拓展的方法student.talk();//子类继承的方法}}输出:1StudentPerson

多态

多态存在的三个必要条件:

继承

重写

父类引用子类对象

Person父类

publicclassPerson{publicvoidsay(){        System.out.println("Person");    }publicvoidrun(){        System.out.println("run");    }}

Student子类

publicclassStudentextendsPerson{//重写say()方法@Overridepublicvoidsay(){        System.out.println("Student");    }publicvoidtalk(){        System.out.println("myStudent");    }}

测试用例

publicclassApplication{publicstaticvoidmain(String[] args){//方法的多态Student student=newStudent();        Person person=newStudent();        Person person1=newPerson();        student.say();//调用Student的say()person.say();//调用Student的say()person1.say();//调用Person的say()}}输出:StudentStudentPerson

原文链接:https://www.sdk.cn/details/voY208AKXddA6L1We9

SDK社区是一个中立的社区,这里有多样的前端知识,有丰富的api,有爱学习的人工智能开发者,有风趣幽默的开发者带你学python,还有未来火热的鸿蒙,当各种元素组合在一起,让我们一起脑洞大开共同打造专业、好玩、有价值的开发者社区,帮助开发者实现自我价值!

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容