1.组合(has a)
public class Car{
private Wheel wheel;
}
class Wheel{
}
2.继承(is a)
class Father{
}
public class Son extends Father{
}
注:Father中的方法如果没有加任何访问权限修饰,那么成员默认的访问权限是包访问权限,它仅允许包内的成员访问。因此如果其他包的类要继承Father,则只能访问public成员。
3.代理
class SpaceShip{
void up(int velocity){}
}
class SpaceShipProxy{
SpaceShip spaceShip = new SpaceShip();
void up(int velocity){
spaceShip.up();
}
}
二. final 关键字
一个即是static又是final的域只占据一段不能改变的存储空间。
1.我们不能认为在编译时,某数据为final就可以知道其值。
比如:
public class Test {
private static Random rand = new Random(47);
private final int num = rand.nextInt(20);
public static void main(String[] args){
Test test = new Test();
Test test2 = new Test();
System.out.println(test.num);
System.out.println(test2.num);
}
}
结果:18
15
2.final允许空值,不过要在使用时,必须进行初始化,但以后就不可改变。
private final int i ; //允许空白final
3.final方法
使用final方法,以防任何继承类修改它的含义。
类中所有的private方法隐式地指定为final的。所有无法覆盖
public class Father {
private void show(){
System.out.println("Father");
}
public static void main(String[] args) {
Father father = new Son();
father.show();
}
}
class Son extends Father{
public void show(){
System.out.println("Son");
}
}
答案:Father
注:java中除了static方法和final方法(private 方法属于final方法),其他方法都是动态绑定的。
4.final类:不允许该类被继承