2015年9月21日 星期一

巢狀式類別

內部類別示範:
public class Car {

    private boolean running = false;
    private Engine engine = new Engine();

    private class Engine {
        public void start(){
            running = true;
            System.out.println("引擎起動中....");
        }
    }
    
    public void start(){
        engine.start();
        System.out.println("汽車狀態: 準備行駛.....");
    }
}

public class Demo {
    public static void main(String[] args){
        Car c1 = new Car();
        c1.start();
    
    }
}

暱名內部類別示範:
public class CarBrand {

    //建立一個內部有暱名類別的物件
    public LandRover l1 = new LandRover(){

        @Override
        public String toString() {
            return ("Land Rover : " + l1.getBrand1());
        }    
    }; //注意節尾的結束符號
            
    // 這是一般的內部類別用法
    private class LandRover {
        private String brand1 = "Defender !";
        public String getBrand1(){
            return brand1;
        }
    }
}

public class Demo {
    public static void main(String[] args){
        CarBrand c1 = new CarBrand();
        System.out.println(c1.l1);
    }
}