Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inheritance

 
putti don
Greenhorn
Posts: 20
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I found this question in one of the mock exam...

Question :
What is the result of compiling & executing the following code ?

class Object {

String str ;

Object ( String str ) {
this . str = str ;
}

public String toString ( ) {
return str ;
}
};

class Ques extends Object{

Ques ( String str ) {
super ( str ) ;
}

public static void main ( String args [ ] ) {
Ques x = new Ques ( " My Object " ) ;
System . out .println ( x. str ) ;
}
};

Options :

a . Compiler error since you cannot redeclare a class that already exists
b . Compiler error since the extends clause does know which Object class to extend from
c . Prints something that denotes the state of the object x
d . Prints My Object

ANS is option d. But when i compiled this program i got error. can anyone please explain what is the correct output?

Thanks.
 
Scott Johnson
Ranch Hand
Posts: 518
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

can anyone please explain what is the correct output?


(D) is correct.

(A) is not valid because we are not redeclaring an existing class. Sun's Object class is in java.lang but this Object class is in the default package.

(B) is incorrect because the Object class is in the same package as the Ques class so the compiler prefers it over java.lang.Object.

(C) is incorrect because str is a String field of the Object class.
 
Thomas Drew
Ranch Hand
Posts: 47
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try removing the simicolons at the end of your class declarations.
 
srikanth reddy
Ranch Hand
Posts: 252
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
it is compiling and printing My Object to the console.....
 
Sandeep Chhabra
Ranch Hand
Posts: 340
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Thomas Drew:
Try removing the simicolons at the end of your class declarations.


Thomas, I dont think semicolons at the end of class decleration affect the proper functioning of the program.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic