包括向上轉型和向下轉型
向上轉型
將子類的物件賦值給父類的參考
一個參考能夠呼叫哪些成員(變數和函式),取決于這個參考的型別
一個參考呼叫的是哪個方法,取決于這個參考所指向的物件
public class Person { String name; int age; Person(String name, int age) { this.name = name; this.age = age; System.out.println("Person 二參構造"); } void introduce() { System.out.println("我的名字是" + name + ", 我的年齡是" + age); } }
public class Student extends Person { String address; public Student(String name, int age, String address) { super(name, age); this.address = address; } void introduce() { super.introduce(); System.out.println("我的地址是" + address); } }
public class Test { public Test() { // TODO Auto-generated constructor stub } public static void main(String[] args) { // TODO Auto-generated method stub Student student = new Student("furong", 12, "BeiJing"); Person person = student; person.name = "quange"; person.age = 13; person.introduce(); } }
運行結果
Person 二參構造
我的名字是quange, 我的年齡是13
我的地址是BeiJing向下轉型
將父類的物件賦值給子類的參考
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/24437.html
標籤:Java
上一篇:為什么使用了索引查實還是慢?
