The following Java exercise(s) are designed for beginner level programmers. If the level is too hard, then I recommend 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: Upcasting an object
What happens when the following program is compiled and run?
public class Super { protected int i = 4; public int method(){ return i * i; } } public class Sub extends Super { int i = 3; public int method(){ return i * i; } public static void main(String[] args){ Super s = new Sub(); System.out.print("-x" + s.method()); System.out.print("-x" + s.i); } }
Quiz 2: Downcasting and upcasting objects in Java
What happens when the following program is compiled and run?
public class MySuper { int z = 3; int myMethod(){ return z; } } public class MySub extends MySuper { int z = 8; int myMethod(){ return z; } public static void main(String[] args){ MySuper mySuper = new MySub(); MySub mySub = (MySub) mySuper; System.out.print("-x" + mySuper.myMethod() + "-x" + mySuper.z); System.out.print("-x" + mySub.myMethod() + "-x" + mySub.z); } }
Article: Java casting object Quizzes: Beginner Intermediate Advanced |
Suggested Articles
![]() ![]() ![]() |
hello sir !
why 4 in the first output ?
By casting objects
s.method() would invoke the overridden method in the subclass, while the attribute is of the type of the superclass. So, s.i refers to the i in the superclass.
Hello world !
i did not understand why in the first code 4 was in the output?
I like what you are up too. This kind of clever work!
Wow, marvelous blog structure! How long have you been running a blog?
i love your blog and its my favorite java website!!
Love the quizzes! I am the beginner and spent over an hour thinking about few questions. Not easy but covers a lot!
The paragon of undrestanding these issues is right here!
First of all, I want to say that your website is awesome! I love all your quizzes and thanks for your great effort.
You are always welcome!
That’s a genuinely impressive answer.
The quality of your posting is there for all to see
I am a beginner Java programmer. Can you tell me please, how long it takes to start with the intermediate level quizzes?
I think you need almost one year experience, but that is not a rule:)
Thanks! Always good to find a real expert.
If inoamrftion were soccer, this would be a goooooal!
I learn everyday from your quizzes!
I am glad to read that!
I told my kids we’d play after I found what I neddee. Damnit.
Big help, big help. And sutrleapive news of course.
Thanks for posting this nice article!
If your aritelcs are always this helpful, “I’ll be back.”
Your articles and quizzes are just great. Keep up the good work!
The answer of an expert. Good to hear from you.
Please, more quizzes!
I update and add content to this website regularly. New quizzes are on the way:)
Just what I’ve been looking for. Thanks!