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

Inheriting instance variables from an abstract class  RSS feed

 
R Johns
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I am trying to declare an instance variable in a parent abstract class and then initialize it in the subclass. While compiling, I am constantly getting an error saying <identifier> expected. If I declare the variable again in the subclass then I'm okay, but I feel that I shouldn't have to do it. The classes are in separate files that are stored in the same directory. Why should I have to declare the variable again in the subclass? Thank you for any help provided!

 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Private variables can't be accessed by other classes, including subclasses.

Also, Java statements that are not declaration statements, must be in an constructor, initializer, or method. It can't just be placed anywhere.

Henry
 
Ganesh Patekar
Bartender
Posts: 696
23
Eclipse IDE Hibernate Java jQuery MySQL Database Netbeans IDE Oracle Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to CodeRanch!    You can read more about access modifiers at this link, click here --->Controlling Access to Members of a Class
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16027
87
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should not declare the variable again in the subclass. In fact, if you do that, you end up with two member variables, one in the superclass and one in the subclass. Very confusing, because they have the same name, but are different variables (and can have different values).

The way to do this is to let the constructor of the superclass initialize the variable, and in the subclass pass the desired value to the superclass constructor.
 
Max Ma
Greenhorn
Posts: 18
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sub classes can not see super classs's private fields
 
R Johns
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you all for the help. First thing I did this morning when I woke up was come back and take a look....I was pleasantly surprised to see all of the helpful responses. I learned a lot.....thanks again. It's working as intended now.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!