public class Student{ private String name; public void setName(String name){ this.name=name; } public String getName(){ return name; }
//父類:動物類 public class Animal{ public int age; public String name; public void eat(){ System.out.println("動物具備吃東西的本領!"); } } //子類:狗類 public class Dog extends Animal { }
//父類:動物類 public class Animal{ public int age; public String name; public void eat(){ System.out.println("動物具備吃東西的本領!"); } } //子類:狗類 public class Dog extends Animal { } //測試類 public class Test{ public static void main(String[] args) { //父類的引用能夠指向本類的對象 Animal ani1 = new Animal(); //父類的引用能夠指向子類的對象 Animal ani2 = new Dog(); } }
不容許經過父類的引用調用子類獨有的方法。 oop
//父類:動物類 public class Animal{ public int age; public String name; public void eat(){ System.out.println("動物具備吃東西的本領!"); } } //子類:狗類 public class Dog extends Animal { public void eat(){ System.out.println("狗是吃肉的。"); } } //測試類 public class Test{ public static void main(String[] args) { //父類的引用能夠指向本類的對象 Animal ani1 = new Animal(); //父類的引用能夠指向子類的對象 Animal ani2 = new Dog(); //輸出動物具備吃的本領 ani1.eat(); //輸出狗是吃肉的 ani2.eat(); } }