It's not a secret anymore!*
The moose likes Beginning Java and the fly likes Accessing inherited protected instance variable question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Accessing inherited protected instance variable question" Watch "Accessing inherited protected instance variable question" New topic
Author

Accessing inherited protected instance variable question

Edward Lawrence
Greenhorn

Joined: Apr 02, 2010
Posts: 21
Given the following 2 classes (Dog.java extends Animal.java), please help me with the 2 questions listed below them.



Question 1 - Why do I get the following compile error for line 5 but get no error for line 4 in Dog.java?

C:\SCJP\CODEPR~1>javac pkgb\Dog.java
pkgb\Dog.java:9: <identifier> expected
System.out.println("1-protected Animal instance variable i = " + i);
^
1 error

Question 2 - How do I access the inherited instance variable i in the main method of Dog.java?


Regards,
Edward
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

Edward Lawrence wrote:
Question 1 - Why do I get the following compile error for line 5 but get no error for line 4 in Dog.java?

C:\SCJP\CODEPR~1>javac pkgb\Dog.java
pkgb\Dog.java:9: <identifier> expected
System.out.println("1-protected Animal instance variable i = " + i);
^
1 error

Statement(except declaration statement) must be inside a block/method .

Edward Lawrence wrote:
Question 2 - How do I access the inherited instance variable i in the main method of Dog.java?

way - 1:
create a instance of subclass/Dog and then access the protected variable of super class which stay in another package.

way - 2:
make the protected variable i as static in super class

hope this helps
Edward Lawrence
Greenhorn

Joined: Apr 02, 2010
Posts: 21
Awesome!! Thanks.
Devaka Cooray
ExamLab Creator
Saloon Keeper

Joined: Jul 29, 2008
Posts: 3029
    
  35

Please don't forget to UseCodeTags when you post a code. It's unnecessarily hard to read the code otherwise.
I've added to the code tags for you.


Author of ExamLab ExamLab - a free SCJP / OCPJP exam simulator
What would SCJP exam questions look like? -- Home -- Twitter -- How to Ask a Question
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Accessing inherited protected instance variable question
 
Similar Threads
Why doesn't polymorphism determine the output in this case?
doubt on private methods
Protected in subclasses
Array Object Question
casting object references.