Intermediate quizzes – Java casting object

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

casting-objects-blue

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();
	}
}

Select the correct answer.


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));
	}
}

Select the correct answer.



Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.
 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

3 Comments

Add a Comment
  1. 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

    1. 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.

  2. This arltcie is a home run, pure and simple!

Leave a Reply

Your email address will not be published. Required fields are marked *