Reputation: 11
Alpha.java
class Alpha {
private void iamprivate() {
System.out.println("iamprivate");
}
}
Beta.java
class Beta {
void accessMethod() {
Alpha a = new Alpha();
a.iamprivate(); // illegal
}
}
A instance of class Alpha should have all the variables and methods of the class.
But, why can not we invoke all the object's methods? Just because some methods are private?
It looks like instances of class don't have the class's private members outside the definition of the class.
Sorry, I am totally beginner. The question may be silly.
Upvotes: 1
Views: 705
Reputation: 68715
But, why can not we invoke all the object's methods? Just because some methods are private?
Private methods are not exposed to the outside world but you can always call a private method within the class.
It looks like instances of class don't have the class's private members outside the definition of the class.
Class possess all the properties whether they are private/public. It is just that private members are restricted from being accessed outside the class.
Upvotes: 1
Reputation: 24998
That is because the method is private
. These can only be accessed by the methods of Alpha
class. If you want to access it in another class, you need to declare it as public
.
Read more here: http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
Upvotes: 1
Reputation: 208944
Your method is private
private void iamprivate() {
It can be used only inside of your class, not by instances. Change it to public
Upvotes: 1