Forums Register Login

Accessing inherited protected instance variable question

+Pie Number of slices to send: Send
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?
+Pie Number of slices to send: Send
 

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
+Pie Number of slices to send: Send
Awesome!! Thanks.
+Pie Number of slices to send: Send
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.
You will always be treated with dignity. Now, strip naked, get on the probulator and hold this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 2553 times.
Similar Threads
Array Object Question
casting object references.
Why doesn't polymorphism determine the output in this case?
doubt on private methods
Protected in subclasses
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 05:20:31.