consider the below class
public class Player {
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
Assume there is another class in the same package
public class Sample {
Player p1 = new Player();
Player p2 = new Player();
Player p3 = new Player();
Player p4 = new Player();
//p1.
}
In this Class accessing the methods p1.setId(int) is not possible unless it is called in side another method
public class Sample {
Player p1 = new Player();
Player p2 = new Player();
Player p3 = new Player();
Player p4 = new Player();
void example () {
int x;
p1.setId(x);
}
}
Inside example p1.setId() is possible . I understand that java is
enabling the access of methods only inside another method. So its more
secure. But I want to make clarification as why such restriction is
there and what concept data abstraction or Encapsulation is shown with
this restriction. Thanks in advance .
That’s complete nonsense.
You’re simply having problems with the syntax rules of the language, which say that inside a class body, you can have only these four things:
You can’t put just any code inside a class, that’s just not how classes are defined. You can use an instance initializer. This works:
But it’s not usually done as constructors are more appropriate for instance initialization.