The following Java exercise(s) are designed for intermediate level programmers. If the level is too hard, then I recommend to select an easier one or you might consider reading my article about this topic, which offers a theoretical explanation including more exercises. Read More: Java Object Casting
Article: Java casting object Quizzes: Beginner Intermediate Advanced |
Quiz 1: Casting objects in Java
What will happen if you try to compile and execute the main method?
public class MySuper { protected int i = 3; public MySuper() { i ++ ; System.out.print("-x" + method(5)); } public int method(){ return i + i; } public int method(int i){ return method() + i; } } public class MySub extends MySuper { int i = 4; public int method(){ return i * i + super.i; } public static void main(String[] args){ MySuper mySuper = new MySuper(); MySuper Mysub = new MySub(); } }
Quiz 2: Upcasting and downcasting objects in Java
What happens when the following program is compiled and run?
public class Super { protected int x = 3; public int method(){ return x + 5; } public int method(int x){ return method() + x; } } public class Sub extends Super { int x = 7; public int method(){ return x * 4 + super.x; } public static void main(String[] args){ Super s = new Sub(); Sub su = (Sub) s; Super sup = new Super(); System.out.print("-" + s.x + "-" + s.method(3) + "-" + su.x + "-" + sup.method(3)); } }
Article: Java casting object Quizzes: Beginner Intermediate Advanced |
Suggested Articles
![]() ![]() ![]() |
Hi Maroof,
I am not able to understand why the value of i = 0 in MySub.method() being called from MySuper.method1(int) in Quiz 1: Casting objects in Java.
Can you explain me the logic behind this
Here below is the explanation.
The statement MySuper Mysub = new MySub(); calls the no-arg constructor of MySuper.
The constructor calls the one integer parameter method.
System.out.print(“-x” + method(2));
The method calls the method with no parameter.
The method with no-parameter is overridden in the subclass MySub.
In MySuper the program tries to access the value of “i” in MySub.
A superclass has no access to its sub classes members. That is why i is 0.
This arltcie is a home run, pure and simple!