Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can sumone explain this to me? regarding attributes

 
Terry Huang
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


why is the output "easy"?

thx
 
aymane chetibi
Ranch Hand
Posts: 175
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
first you are missing a semi colon. try to find it.
second if you put this semicolon back the output is not easy the output is :
Cannot find symbol
symbol : method printDifficulty()
location: class SCJPExam
myExam.printDifficulty();

regards,
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think he meant to have SCJPExam extends Exam.
 
aymane chetibi
Ranch Hand
Posts: 175
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes Lynn,

with inheritance the output is easy.
the method in protected so it can be inherited.
what about the member variable ?
does the subclass has 2 variables with the same name and 2 different values ???
or is it just that the method access the member in its class first ??

Can you explain this Lynn?

regards,
 
Keith Lynn
Ranch Hand
Posts: 2409
 
NS Reddy
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Exam {
protected String difficultyLevel="easy";
public void printDifficulty(){
System.out.println(difficultyLevel);
}
}

class SCJPExam extends Exam {
private String difficultyLevel="killing";
//public void printDifficulty(){
//System.out.println(difficultyLevel);
//}
public static void main(String args[]) {
SCJPExam myExam=new SCJPExam();
myExam.printDifficulty();
}
}

Since the subclass SCJPExam did not override the printDifficulty() method super class's printDifficulty() method is invoked and hence prints easy.

If the comments are removed in the above program it would print:
killing

Thanks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic