Java: Type casting of objects

Java can cast objects from inherited classes.

class Acast {
	int a = 1;
}

class Bcast extends Acast {
	int b = 2;
}

class Ccast extends Bcast {
	int c = 3;
}

class TestCasting {
	public static void main(String args[]) {
		Acast refA; //Declare object refA of type Acast
		//Create object of Ccast class in object reference variable refA of type of Acast
		//If there is no inheritance, an error will occur.
		refA = new Ccast();
		System.out.println("the value of refA.a: " + refA.a);
	}
}
object type conversion example 1
//Example of error occurrence 1
class Acast {
	int a = 1;
}

class Bcast extends Acast {
	int b = 2;
}

class Ccast extends Bcast {
	int c = 3;
}

class TestCasting {
	public static void main(String args[]) {
		Acast refA; //Declare object refA of type Acast
		//Create object of Ccast class in object reference variable refA of type of Acast
		//If there is no inheritance, an error will occur.
		refA = new Ccast();
		System.out.println("the value of refA.a: " + refA.c); //Attempting to access c, a member of the Ccast class, generates an error
	}
}
object type conversion example 2
//Example of error occurrence 2
class Acast {
	int a = 1;
}

class Bcast extends Acast {
	int b = 2;
}

class Ccast extends Bcast {
	int c = 3;
}

class TestCasting {
	public static void main(String args[]) {
		Ccast refC = new Acast(); //Error occurred
		System.out.println("the value of refC.a: " + refC.a);
	}
}
object type conversion example 3
class A {
	void callme() {
		System.out.println("Executing the callme() method of class A");
	}
}

class B extends A {
	void callme() { //Overridden method
		System.out.println("Execute class B's callme() method");
	}
}

class C extends A {
	void callme() {
		System.out.println("Executing class C's callme() method");
	}
}

class OverridingCast {
	public static void main(String args[]) {
		A r = new A();
		r.callme();
		r = new B();
		r.callme();
		r = new C();
		r.callme();
	}
}
object type conversion example 4

Share This Post

댓글 남기기

이메일은 공개되지 않습니다. 필수 입력창은 * 로 표시되어 있습니다

Latest Post