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

Access private members from a constructor of another class?  RSS feed

 
Hai Thompson
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have this class with 2 private members,

Then I try to create a constructor links to that class, and I get stuck accessing those private variables.

I know that private member must be accessed by only it's class, but I can't figure out any way to do it, I try to create setter from MyClass but it still doesn't work


What I am missing?
 
A.J. Côté
Ranch Hand
Posts: 417
Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hai Thompson wrote:I have this class with 2 private members,

Then I try to create a constructor links to that class, and I get stuck accessing those private variables.

I know that private member must be accessed by only it's class, but I can't figure out any way to do it, I try to create setter from MyClass but it still doesn't work


What I am missing?


Hello,



Maybe a cleaner way::


Alternative way:

 
Hai Thompson
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is brilliant! Thank you very much! My problem is resolved.
 
Mike. J. Thompson
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would add a constructor to your first class and use that to set the variables. That way the object will be immutable, which is normally a good thing.
 
Hai Thompson
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mike. J. Thompson wrote:I would add a constructor to your first class and use that to set the variables. That way the object will be immutable, which is normally a good thing.

I did what you said, do you mean this?

I don't know when I should initialize object in declaration and when I should not (like above).
 
Knute Snortum
Sheriff
Posts: 4073
112
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Setting x and y to zero is not necessary, but it doesn't hurt anything.


This makes your object immutable, that is, once it's created it does not change (as long as you don't add setters).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!