[Java]

조현호_ChoHyeonHo·2025년 1월 9일

Singleton implementation via constraining constructor using modifier

...생성자를 통해 직접 인스턴스를 생성하지 못하게 하고 public메서드를 통해 인스턴스에 접근하게 함으로써 사용할 수 있는 인스턴스의 개수를 제한할 수 있다....
또 한가지, 생성자가 private인 클래스는 다른 클래스의 조상이 될 수 없다. super()로 생성자가 호출돼야 하는데 private에서 막히기 때문이다.

public class SingletonTest {
    public static void main(String[] args) {
        // Singleton s = new Singleton(); -> error!
        Singleton s = Singleton.getInstance();
    }    
}

final class Singleton{
    private static Singleton s = new Singleton();

    private Singleton(){
        //..
    }

    public static Singleton getInstance(){
        if(s == null){
            s = new Singleton();
        }
        return s;
    }
}

Combination of modifier

  1. static and abstract cannot be used together for a method.(static method should have the body part)
  2. abstract and final cannot be used together for a class(for final represents it cannot be extended, abstract does it should be extended.)
  3. abstract method cannot be private method.(similar matter as above)
  4. There is no need to use private and final together on a method. (for private method cannot be overrided if it is final.)

Polymorphism

참조변수가 사용할 수 있는 멤버의 개수는 인스턴스의 멤버 개수보다 같거나 적어야 하는 것이다.

Suppose we have TV and CaptionTv classes like below.

class TV{
	boolean power; 
    int channel;
    
    void power(){	power = !power; 	}
    void channelUp() {	++channel;	}
    void channelDown() {	--channel;	}
}

class CapitonTv extends Tv{
	String text;
    void caption() {}
}

then refer them like this

CaptionTv c = new CaptionTv();
Tv t = new CaptionTv();

Then the reference variable c and t refer same instance(CaptionTv) as this.

그렇다면, 인스턴스의 타입과 일치하는 참조변수를 사용하면 인스턴스의 멤버들을 모두 사용할 수 있을 텐데, 왜 조상타입의 참조변수를 사용해서 인스턴스의 일부 멤버만을 사용하도록 할까? 이에 대한 답은 앞으로 나올것.

Casting of reference variable

형변환은 참조변수의 타입을 변환하는 것이지 인스턴스를 변환하는 것은 아니기 때문에 참조변수의 형변환은 인스턴스에 아무런 영향을 미치지 않는다. 단지 참조변수의 형변환을 통해서, 참조하고 있는 인스턴스에서 사용할 수 있는 멤버의 범위를 조절하는 것뿐이다.

public class CastingTest1 {
    public static void main(String[] args) {
        Car car = null;
        FireEngine fe = new FireEngine();
        FireEngine fe2 = null;

        fe.water();
        car = fe; // implicit up casting casting has done. = car = (Car) fe;
        // car.water(); -> error
        fe2 = (FireEngine) car; // down casting should be done explicitly. 
        fe2.water(); 
    }    
}

class Car{
    String color;
    int door;

    void drive(){
        System.out.println("drive, brrr~~~");
    }

    void stop(){
        System.out.println("stop!!");
    }
}

class FireEngine extends Car{
    void water(){
        System.out.println("water!!");
    }
}

What happens when you run the code...


even the car refers FireEngine eventually, it cannot use the added member of FireEngine since it is declared as a Car, which has fewer members than its childs.

자바 캐스팅은 참조변수가 사용할 수 있는 인스턴스의 멤버의 범위를 줄이거나(업캐스팅) 늘리는(다운캐스팅) 기능이다.

profile
Behold the rabbit hole

0개의 댓글