多態
一種類型的變量可以引用多種實際類型的對象
如
package ooplearn;public class Test {public static void main(String[] args) {Animal[] animals = new Animal[2];animals[0] = new Dog();animals[1] = new Cat();for (Animal animal : animals){animal.eat();}}
}class Animal {public void eat() {System.out.println("Animal eat");}
}class Dog extends Animal{public void eat(){System.out.println("Dog eat");}
}class Cat extends Animal{public void eat(){System.out.println("Cat eat");}
}
Animal類型的變量animal可以引用Dog和Cat類型對象,稱為多態。Animal就是animal變量的靜態類型,Dog和Cat就是animal變量的動態類型。animal.eat()調用的是變量動態類型的方法,稱為動態綁定。
靜態綁定
package ooplearn;public class Test {public static void main(String[] args) {Dog d = new Dog();Animal a = d;System.out.println(d.title); // return DogSystem.out.println(a.title); // return Animal}
}
class Animal {public static String title = "Animal";
}class Dog extends Animal{public static String title = "Dog";
}
變量d的靜態類型是Dog,訪問Dog變量和方法,變量a的靜態類型是Animal,訪問Animal的變量和方法。訪問綁定到變量的靜態類型,稱靜態綁定。
實例方法調用順序
package ooplearn;public class Test {public static void main(String[] args) {Animal[] animals = new Animal[2];animals[0] = new Dog();animals[1] = new Cat();for (Animal animal : animals){animal.eat();}}
}class Animal {public void eat() {System.out.println("Animal eat");}
}class Dog extends Animal{public void eat(){System.out.println("Dog eat");}
}
class Cat extends Animal{
}
上述代碼返回
Dog eat
Animal eat
循環輸出的過程animal變量的實際類型分別為Dog和Cat,先從實際類型找方法,找不到就去父類找。
內部類
定義在類里的類稱為內部類,一般與外部類(包含內部類的類)關系密切,與其他類關系不大。一般對外隱藏,有更好的封裝性。如Swing編程中為組件創建ActionListener:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;public class TwoButtons {JFrame frame;JLabel label;public static void main(String[] args) {TwoButtons gui = new TwoButtons();gui.go();}public void go() {frame = new JFrame();frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);JButton labelButton = new JButton("Change Label");labelButton.addActionListener(new LabelListener());JButton colorButton = new JButton("Change Circle");colorButton.addActionListener(new ColorListener());label = new JLabel("I'm a label");MyDrawPanel drawPanel = new MyDrawPanel();}class LabelListener implements ActionListener {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stublabel.setText("Ouch!");}}class ColorListener implements ActionListener {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubframe.repaint();}}
}
權限修飾符
修飾 | 本類 | 本包 | 其他包子類 | 其他包 |
---|---|---|---|---|
private | Y | N | N | N |
不寫 | Y | Y | N | N |
protected | Y | Y | Y | N |
public | Y | Y | Y | Y |
private修飾部分只能在本類中使用;缺省狀態下,可見性上升到當前包內,即在同一個包內的地方可以使用;protected范圍還包括本包之外其他包屬于自己子類的部分;public沒限制。