• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Please explain this

 
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here is the Question


Source:http://www.hitechskill.com/testengine.jsp


Which one of the following is the simplest way to print the value of variable text at line no. 18?Select one correct answer.

1 class Message
2 {
3 String text="Hello1";
4 }
5 class Super
6 {
7 Message msg=new Message();
8 }
9 class inheritance extends Super
10 {
11 public static void main(String arg[])
12 {
13 inheritance i=new inheritance();
14 i.print();
15 }
16 public void print()
17 {
18 //Here
19 }
20 }

Choice 1 System.out.println(msg.text);
Choice 2 System.out.println(super.msg.text);
Choice 3 System.out.println(Message.text);
Choice 4 System.out.println(text);


I thought like this:

choice 1 is the only correct answer.

But when I run on my machine if I insert choice2 also at line 18 it is compiling fine and giving same o/p.

Can anybody please explain what does super.msg.txt indicate?
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The super keyword is used to explicitly access a member in the superclass.

As you can see in the code, class Super is the superclass of class inheritance, and msg is an instance variable in Super. So in class inheritance, you can use super.msg to explicitly refer to the member variable msg in inheritance's superclass.

See: The Java Tutorials - Using the Keyword super
 
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When you use "msg.text" , it prints from the inherited(Inheritance extends Super) msg variable and when you use "super.msg,text", the msg variable of super class (Super) is used to print the value of text.
 
Hey! Wanna see my flashlight? It looks like this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic