开发者

What does it mean for a method to be public/private/other in java? [closed]

开发者 https://www.devze.com 2022-12-27 14:06 出处:网络
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references,or expertise, but this question will likely solicit debate, a
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. 开发者_开发知识库 Closed 10 years ago.

What does it mean for a method to be public/private/other in java?

What are the advantages and disadvantages of these options?

What is my impetus, as someone trying to be a good programmer, to care?


When a method is public it means it can be accessed by other objects

For instance:

class David {
     // public method, can be use by anyone
     public String getName() {
         return "David";
      }
 }

The method getName may be accessed by other classes because it is public:

 class Other  {
      David davidOne = new David();
      String davidsName = davidOne.getName(); //<-- compiles and runs
 }

The advantage.. well you can use it from other places.

When a method is private it means it can only be accessed by objects OF THE SAME CLASS

For instance, in this new definition:

class David {
     public String getName() {
         return "David";
     }
     // private method... nobody but David's "instances" can use it.. 
     private int getAge() {
         return 19;
     } 

 }

The method getAge can't be accessed by other classes because it is private, if you try to do it, the compiler will give you an error message:

 class Other  {
      David davidOne = new David();
      String davidsName = davidOne.getName(); 
      int davidsAge = davidOne.getAge(); //<-- Compiler error, getAge() is not visible
 }

But, if you can use it within David class:

class David {
     public String getName() {
         return "David";
     }
     // private method... nobody but David's "instance" can use it.. 
     private int getAge() {
         return 19;
     } 
     // Here the call to "getAge()" will succeed, because it is visible 
     // inside the class 
     public boolean hasSameAgeAs( David otherDavid ) {
         return this.getAge() == otherDavid.getAge();
     }
 }

The advantage? You can create a bunch of methods and keep them private, avoiding data corruption or in general preserving your objects encapsulated

About encapsulation

In OOP ( object oriented programming ) the intention is to model the software after real life objects.

Real life objects have ( among other things ) attributes and methods to access those attributes.

You want to make public some of those methods, and keep private others.

For instance, a Human being, have a heart. But it is not exposed to everybody, it would be dangerous. It is encapsulated inside our body.

If we were to model a software after a real Human we may declare the method: heartBeat as private ( so, nobody can access it )

In the other hand, it would be useful to have come public methods like getGender to find out if your Human instance is male or female.

There are other access modifiers such as: "protected" and package protected ( whose doesn't have a keyword )

 class David {
      // protected method
      protected int getBalance() { 
          return 1000000; 
      }
      // package protected or "default" method
      boolean knowsOop(){ 
          return true;
      }
 }

There the method getBalance can only be accesed by David instances and David subclasses ( create another thread for what is a subclass )

The method knowsOop can be accesses by anyone inside the package as David is defined.

Don't worry about this two access modifiers, they will make sense when you learn more about OOP and Java.

Finally you should really, really take time to read:

http://java.sun.com/docs/books/tutorial/java/javaOO/index.html

I hope this helps


A public method can be accessed from everywhere, a private method only from the same class. The main advantage is the control over the API of an class. If I make only public what is needed, I can change the internal behaviour of a class , without breaking code depending on this class. You should care, because software changes often in the real world (at least it's my experience and others have it too) and the more every change breaks, the more energy you have to put into maintenance or the more bugs your software has. In the end it's a question of costs.

The possibility to hide internals of your class from users of this class to avoid breaking code by later changes is often called encapsulation or information hiding.

The two options besides public and private are package (without an modifier) and protected. The package-accessible method can also be accessed from within classes of the same package. I cannot remember to used that option in any useful way. protected methods can be accessed from classes, that inherit the class in question. That is often used to create classes with concrete behaviour for a defined API of the base-class. For example could you implement a new List-class by extending AbstractList and you only need to implement get and size (and one set-method for modifiable lists). The other methods exposed by the API of List are defined in the base-class, calling the three other methods if needed.


Private methods can be called only inside the class. You can call public methods of your class anywhere in program. Methods without access modifier are meant to have package visibility scope (it's called default), so you can invoke it anywhere in package, where class is defined.

See http://en.wikipedia.org/wiki/Object_oriented_programming#Encapsulation


HThe public, protected and private modifiers control what other code can see those methods (or fields). It's about controlling the interface you're exposing.

The commonly useful ones are:

The public modifier: any other can see your method.

The private modifier: no code other than your class and any inner classes can see your method.

These would be useful for example if you wanted to ensure there was only a single instance of a class ever created (singleton pattern). You could make the constructor private, create a single instance and store is as a private member called instance, and provide a public method something like this:

public static MyObject getInstance() {
  return instance;
}

and so you can guarantee that there will only every be one instance.


Update - another example as requested.

Another example might be where you have a complicated public method and you want to break it down into simpler parts. You could break it down into simplr methods, each doing part of the job, but you wouldn't want other code to call those part methods, as they wouldn't work on their own - so you would make the smaller methods private, ensuring that they can't be called outside your class.


the main reason is called encapsulation: don't give access to internal state of object.


For starters, I would to start restrict the access as much as possible. Start with private. If you happen to need the constructor, method or field from somewhere else, but cannot access it due to the restriction, then the next steps would be to ask yourself:

  1. If it is a method, do you really need to access it? Does it change the behaviour of the class/instance? Shouldn't you let that class do the work? Shouldn't the current class (which needs that field or method) be brought tighter to that class?
  2. If it is a field, do you need to get or set its value? Shouldn't you add a method which does exactly that?

Point 1 avoids wrong coupling and point 2 improves encapsulation. Once you've considered the above and concluded that less restriction is really needed, then set it one step or more further open.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号