← Back to feed
Renewal·서른의 생활코딩

ex11) Java OOP - Type Casting

NS
normalstory
cover image

class Acast { int a=1;}
class Bcast extends Acast{ int b=2;}
class Ccast extends Bcast{ int c=3;}


public class TestCast {

public static void main(String[] args) {
Acast refA;
refA = new Ccast();
//understanding access scope 1
System.out.println("refA.a's value is "+refA.a);
//System.out.println("refA.a's value is "+refA.b); 
//System.out.println("refA.a's value is "+refA.c);

//understanding access scope 2
//Ccast cc = refA; 
Ccast cc = (Ccast)refA; //forced type casting
System.out.println("refA.a's value is "+cc.a);
System.out.println("refA.a's value is "+cc.b); 
System.out.println("refA.a's value is "+cc.c);
//access scope check 3
Bcast bb;
bb = new Bcast();
System.out.println("refA.a's value is "+bb.a);
System.out.println("refA.a's value is "+bb.b); 
//System.out.println("refA.a's value is "+bb.c);
//System.out.println("refA.a's value is "+((Ccast)bb).c); //anyway member since it is not
Ccast c1;
//c1 = new Bcast();
Bcast b1 = new Bcast();
//c1 = b1;
//c1 = (Ccast)b1;//anyway member since it is not

}

}

This English version was translated by Claude.

친절한 찰쓰씨
Written by
친절한 찰쓰씨

Pleasant Charles — UI/UX researcher at AIT. Keeping notes on design, planning, and slow days here since 2010.