//[1]What is the Error?
class A{
public int i;
public void seti(int ii){
i =ii;
}
public void printi(){
System.out.println("i = "+i);
}
}
class B extends A{
public void modi(){
i = i+8;
}
}
class TestC8{
public static void main(String...arg){
A ob1 = new A();
B ob2 = (B)ob1; //we try to cast super class to sub class
}
}
//Note:
// Rule : cast super class ref var to sub class
// it is Ok at compile time but failes at runtime!!
--------------------------------------------
//[2]What is the output?
class A{
public int i;
public void seti(int ii){
i =ii;
}
public void printi(){
System.out.println("i = "+i);
}
}
class B extends A{
public void modi(){
i = i+8;
}
}
class TestC7{
public static void main(String...arg){
A ob1;
B ob2 = new B();
ob1 = ob2; //super class is reffering subclass object
ob1.seti(6);
ob1.printi();
B ob3= (B)ob1; //casting super class var to sub class
ob3.modi();
ob3.printi();
}
}
class A{
public int i;
public void seti(int ii){
i =ii;
}
public void printi(){
System.out.println("i = "+i);
}
}
class B extends A{
public void modi(){
i = i+8;
}
}
class TestC8{
public static void main(String...arg){
A ob1 = new A();
B ob2 = (B)ob1; //we try to cast super class to sub class
}
}
//Note:
// Rule : cast super class ref var to sub class
// it is Ok at compile time but failes at runtime!!
--------------------------------------------
//[2]What is the output?
class A{
public int i;
public void seti(int ii){
i =ii;
}
public void printi(){
System.out.println("i = "+i);
}
}
class B extends A{
public void modi(){
i = i+8;
}
}
class TestC7{
public static void main(String...arg){
A ob1;
B ob2 = new B();
ob1 = ob2; //super class is reffering subclass object
ob1.seti(6);
ob1.printi();
B ob3= (B)ob1; //casting super class var to sub class
ob3.modi();
ob3.printi();
}
}
No comments:
Post a Comment