• Post Reply Bookmark Topic Watch Topic
  • New Topic

inherited variables.  RSS feed

 
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i have a class with a variable of type int.



I am extending this class.



why does the assignment in class B gives a compilation error?Can we not use inherited variables directly in the derived class?
What are the rules to be followed while initializing a derived variable?
 
author
Sheriff
Posts: 23295
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
Vidur Koushik wrote:
why does the assignment in class B gives a compilation error?Can we not use inherited variables directly in the derived class?
What are the rules to be followed while initializing a derived variable?


Java statements, which is what an assignment is, must be either in a constructor, initializer, or method. You can't just have random statements anywhere in a class.

Henry
 
Vidur Koushik
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@Henry Wong
Thank You.
 
Vidur Koushik
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A small doubt.
If initialization cannot be done in body of class, why does this not throw compilation errors?

 
Henry Wong
author
Sheriff
Posts: 23295
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

Declarations are a different case. You can declare variables at instance and class scope -- for instance and static variables respectively. And of course, declarations may also have an optional initialization component.

Henry
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!