编程思想-复用类

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类:不允许该类被继承

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值