Java 类的封装、继承、多态
生活随笔
收集整理的這篇文章主要介紹了
Java 类的封装、继承、多态
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
// 封裝、繼承、多態
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);}@Overridepublic 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();// 多態,父類對象通過子類實例化,調用的是子類的talkStudent s2 = (Student) p;//向下類型轉換,需要強制,向上是自動轉的s2.talk();// 如果 p 是由 Person1 new 出來的,此處報錯}
}
輸出:
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總結
以上是生活随笔為你收集整理的Java 类的封装、继承、多态的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 流畅的Python 1. Python数
- 下一篇: LeetCode 2185. 统计包含给