• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Accessing a class member from another class

 
pagano monello
Ranch Hand
Posts: 38
1
Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am a little bit confused about how to access a member of a class from another class. What lets me really surprised is that I have noticed just now that, if I want to access a member of a class from another class, it seems that I'm forced to be inside a method, or a constructor, but I cannot understand why. I try to explain better my issue with an example.
I suppose to have two classes, Book and Library (same package), and I try to access a member of Book from Library. If I try to do it in the following manner it doesn't work:

but if I include the assignation statement inside a method (meaninglessMethod), now it works:

Actually I cannot understand why.
I am sorry if the explanation of the issue is not so clear, I tried to explain as better as I can.
Thank you in advance.
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's not related to access members of another class. It applies to members of the same class as well. The following code won't compileAnd you can fix it using some alternativesAnd you could of course initialize the variable i in a method as well, but that would not be the equivalent of the X class.

In the body of the class you can only have field, constructor, initializer block and method declarations. Setting a property (like you tried), printing a value,... should be done in a constructor, initializer block and/or method.

Hope it helps!
Kind regards,
Roel
 
Campbell Ritchie
Sheriff
Posts: 51332
86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is of course not at all good to have non‑private fields. That should have read
 
pagano monello
Ranch Hand
Posts: 38
1
Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you both, really, for your answers.

Roel De Nijs: your explanation is definitely spot-on. I'm going to ponder really carefully about what you told me.

Campbell Ritchie: thanks for warning me about the fact that it's wrong let direct access to an object's attribute.

Thanks again.
pagano
 
Campbell Ritchie
Sheriff
Posts: 51332
86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic