It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
What is the benefit of using public private protected keywords in method declarations?
I can imagine the benefit of public private protected keywords for variables because it will prevent unnecessary "value change" by objects outside the particular class
but I cannot imagine the benefit of putting the keyword "private" or "public" or "protected" in method declarations.
If there is a method, it is my belief that the only object(s) that can use the method is the object that contains that method anyways?
First of all, let's clarify the meaning of public, protected, package, and private access. In each case, you are correct that an object must exist to use a non-static method. However, these keywords indicate who is allowed to invoke the method on the object:
public methods can be invoked by anyone.
protected methods can be invoked by any class in the same package or subclasses in other packages.
package private methods (without any access modifier) can be only invoked by classes in the same package.
private methods can be invoked only by the same class.
As an example, I often use private methods to factor out code which is otherwise repeated among several different methods. This code isn't part of the public interface for other classes to use. Rather, it is a "worker" method that does some of the calculations internal to the class itself.
public means the method can be override, and is available for use by any code for which the enclosing class is visible.
private means the method is usable only by the enclosing class.
protected means that the method is callable only by the enclosing class, and any class that extends that class.
package (no keyword before the method) means that the method can be called by any code within a class in the same package as the enclosing class.
In Java, difference between default, public, protected, and private
These different keywords are useful in designing how your class will be used. public methods are part of the "contract" you are exposing to the users of your class. private methods are typically implementation code that should not be exposed in any way to the outside world because you want to hide that logic in case you want to replace or modify it in the future without breaking your "contract" with the class' users.
protected methods are available to classes that extend your class. So maybe there's some implementation that you want to make available for overriding -- or perhaps you need an extending class to implement this method in order to make your class work, but it's not part of the "contract" your exposing to callers of your class or those calling the extending class.
Use package to create implementation code that other classes in the package can call, but that you don't want to expose to those using your class (not part of your "contract" with your users.) I use package level methods if I need to test some tricky implementation code from a unit test, but don't want to make the method public.
To understand the benefit of restricting access to a method, consider this : You can safely change or even remove a private method from a class, because you know it's only ever accessed from within that class. If you are publishing an API, and you expose a public method, then its out there for good. If you try to change it, you will break code that relys on it being available. You have to think about how code will evolve over time to fully appreciate this.
If there is a method, it is my belief that the only object(s) that can
use the method is the object that contains that method anyways?
No, not true. Methods can be declared static, which means they do not require an object to be invoked on.
Related
This question already has answers here:
Is it possible to hide or lower access to Inherited Methods in Java?
(8 answers)
Closed 5 years ago.
I am writing a program where there are quite a lot number of methods in a particular class, so I decided to write an abstract class to help in keeping track of the methods.
Now, consider this: I have declared a method as abstract in the abstract class, and in the other class (which extends the abstract class), I want to override this method, but with access privilege reduced to private. Here, the compiler is giving a problem. It says that an attempt to assign weaker access privileges is being met with, which cannot be allowed. If I try to declare the method in the abstract class as protected (I have also changed the private ones to protected in the sub-class), it says that modifiers abstract and protected cannot be used together.
So, what can I do? Do I have to make the methods package access or public in both classes? If so, is there no way that I can declare these methods private?
Please note that I'm asking only for abstract classes, and not all classes in general.
What do you mean it can not be protected abstract - of course it can.
And the thing that you want to do is basically prohibited by the compiler and the language itself in the first place.
The answer to your question is: there's nothing you can do to reduce the visibility of a method declared in a parent class.
If you can restate what you're trying to accomplish by "keeping track of the methods" in an abstract parent class, you might get a different solution.
So, I'm beginning to learn Java and I think it's an awesome programming language, however I've come across the static keyword which, to my understanding, makes sure a given method or member variable is accessible through the class (e.g. MyClass.main()) rather than solely through the object (MyObject.main()). My question is, is it possible to make certain methods only accessible through the class and not through the object, so that MyClass.main() would work, however MyObject.main() would not? Whilst I'm not trying to achieve anything with this, I'd just like to know out of curiosity.
In my research I couldn't find this question being asked anywhere else, but if it is elsewhere I'd love to be pointed to it!
Forgive me if it's simple, however I've been thinking on this for a while and getting nowhere.
Thanks!
Any static method or member belongs to the class, whereas non-static members belong to the object.
Calling a static method (or using a static member) by doing myObject.method() is actually exactly the same as MyClass.method() and any proper IDE will give a suggestion to change it to the second one, since that one is actually what you are doing regardless of which of the two you use.
Now to answer the actual question:
is it possible to make certain methods only accessible through the class and not through the object
No, not as far as i know, but like I said, any proper IDE will give a warning, since it makes little sense and it gives other readers of the code an instant hint that you're dealing with static members.
Yes, short answer is no.
But you can put your static members in a dedicated class, so that no instances share any one of them.
MyObject is instance of MyClass, and you aggregate all you static parts in MyStaticThing.
Using static member on an instance can be misleading, so it is a bad practice
http://grepcode.com/file/repo1.maven.org/maven2/org.sonarsource.java/java-checks/3.4/org/sonar/l10n/java/rules/squid/S2209.html
While it is possible to access static members
from a class instance, it's bad form, and considered by most to be
misleading because it implies to the readers of your code thatthere's
an instance of the member per class instance.
Another thing, do not use static things, because you cannot do abstraction and replace implementations to extend your code.
Being able to switch between implementations is useful for maintenance and tests.
In Java, you can crete an object with these keywords.(new keyword, newInstance() method, clone() method, factory method and deserialization) And when you create an object,it can also use classes abilities which is like static methods.
Short answer:No.
Is it possible to make certain methods only accessible through the class and not through the object?
Yes, it is. You achieve this by preventing any instances of the class to ever be created, by making the class non-instantiable: declare its constructor private.
public final class NonInstantiable {
private NonInstantiable() {
throw new RuntimeException(
"This class shouldn't be instantiated -- not even through reflection!");
}
/* static methods here... */
}
Now, it only makes sense to declare any methods of the class static -- and they can only be called through the class name. Such a class is often called a utility class.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
In C# the spec says:
Instance constructors, destructors, and static constructors are not
inherited, but all other members are, regardless of their declared
accessibility (§3.5). However, depending on their declared
accessibility, inherited members might not be accessible in a derived
class.
so private fields are inherited into a derived class but they are not accessible.
However the Java spec says:
Only members of a class that are declared protected or public are
inherited by subclasses declared in a package other than the one in
which the class is declared.
so private fields are not inherited into a derived class.
And what does explain the OOP theory? Is correct C# or Java designers?
A bit confused on this aspect.
P.S.
I haven't C++ experience? What does C++ designers says on this?
Well, the C# version is more-clear because even in Java, private fields will be available as part of the child object but they will no be directly accessible unless you have a public getter in the parent class to get its value.
You can actually use reflection to make private fields (of the parent ) accessible and read their values directly.
Keeping the things simple and clean, taking some part of quote you mentioned for c++
However, depending on their declared accessibility, inherited members might not be accessible in a derived class.
The same thing happens in Java as well. You can't access private fields in Java too.
There are methods around them to access which is another story (encapsulation)
Answering at least the C#/Java-part as I don´t know much on C++.
However, depending on their declared accessibility, inherited members might not be accessible in a derived class.
The C#-spec seems to be a bit more meaningful, although Java handles private mebers the same way. The private members from base-class also exist in Java (however they are not inherited, see are private fields inherited in Java?). As you cannot access them this is not usefull anyway. The internals however are of course initialized by setting the private members also. So instances of your derived class of course have all the private members of the base-class, inheritance however means any kind of polymorphism which implies you might be able to override (assuming your member is not static or final/selead) them which makes no sense at private members.
So coming to the chase there should be no need for accessing the internals at all, neither in C# nor in Java nor anywhere else. Simply assume your derived instances get all the base-members fully-initialized and do your actual work.
Relating to what you call "OOP-theory" I doubt there is a cleaner answer as for this principle (which is implemented in different ways in the mentioned languages)private members have no relevance at all. OOP merely handles the interactions between objects with their surrounding not their actual internals.
I think the confusion is related to a confusing wording. In Java or C# or any other OO language, if you construct a child you have to call the parent constructor, because the parent is part of the child. Very often the call of the parent constructor is done implicitly.
So the private attributes from the parent are always present somewhere within the child object. Then OOP ensures, that you can not access the private attributes within the child. This encapsulation is the important point. And this fact is described by the two references: Either you call it the attributes are not inherited or you say that they are inherited but not visible.
As mentioned above you can (ab)use the reflection library to get around these restriction.
This question already has answers here:
What is the difference between public, protected, package-private and private in Java?
(30 answers)
Closed 7 years ago.
I am learning Java and there's something bothering me and the textbook doesn't explain it.
I understand that you use modifiers to declare methods inside classes and all. But I suddenly got to a class declared like
static void(){
}
Why is there no public or private modifier and it still works? Can I avoid using the public modifier everywhere else or how does that work? I understand that static means member of the class and void that it doesn't return a value. Yet why not public or private for that matter.
For the sake of this explanation, the terms "functions" and "methods" are used interchangably. There is a small difference between them, for more information, ask Google.
Methods in Java that do not explicitly specify a modifier are by default package-private, so the method is visible to all the classes in the same package as the class where the method is declared.
Public functions are callable by all classes that have access to the class (i.e your whole project) and private methods are only callable within the class the method was written in. There is also the protected modifier, which specifies that the functions can only be accessed by the class, all its subclasses and classes in the same package.
"Why is that important?", you may ask. Good question!
You should use modifiers to hide methods/properties from other classes which may (ab)use them or in a bad case could lead to unexpected behaviour (not necessarily technically, but semantically... some methods just need a little more privacy just like we do). So a good place to start is private, which means only the class it is declared in is able to call it. More often than not, you'll need to give other classes access to methods, which is why the package-private, protected and public modifiers exist.
Data encapsulation is an important paradigm in programming, and these modifiers help you achieve just that.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
When we can have class and method as static?
Anybody please help me with some example...
When you don't need a class instance to invoke that method. It means that method does not depend on any non-static members of the class
You can make a method static if it doesn't use any non-static members of the class.
You can make a class static if it only contains static members.
If a method doesn't change it's behaviour based on different objects of it's enclosing class. it can be marked static.
Check Math class. all of it's methods are static cause, their behaviour just depends on the argument within methods and those methods don't make any change in the class states.
All the utility/helper methods can be (should be) marked as static. i.e. if their behaviour is same for all objects, why to have different copy for each object, just have one copy and let all objects share same copy.
You should check this also: Why are you not able to declare a class as static in Java?
A static method belongs to the Class and thus not to a specific instance. If you think at programming languages in term of message dispatching we can say procedural programming provides only 1 level of message dispatching as the name of the function correspond to its actual behavior. In Object Oriented Programming we have two level of message dispatching as you also has you have to specify an object plus the signature of a function (method). The same function may behave differently on different object depending on their status (subClass overridden method, etc.). A static method is instead like a global function you can execute where and how you want and always has the same behavior.
You may therefore limit the usage of static methods although there are cases in which they are helpful. In the Singleton pattern (http://it.wikipedia.org/wiki/Singleton) a static method is necessary to retrieve the Singleton's instance (also a private static attribute is necessary to keep track of it).
For those who claim Singleton are evil and you should always use Dependency Injection via Google Guice, also Guice relies on static method for instance to create an injector (http://lowcoupling.wordpress.com/2012/12/05/dependency-injection/).
So I guess the best answer is you should always think if the problem you are facing might just be solved by the injection of object but there are cases in which the usage of static methods is pretty reasonable.