I'm learning Java and I just wonder why public and private is used when a method or members is static? When static is used they are class methods and class members and could be used from other classes without creating an object, so is public and private necessary? Some help is preciated to understand. Sorry if this question is too simple for some.
The accessibility of a field or method is orthogonal to the fact that it's static or not.
You could have a static method accessible from the outside, and a static method that must only be used from inside the class itself (by other static or non-static methods). The same goes for fields.
For example:
// not visible from the outside
private static final long MILLISECONDS_IN_A_MINUTE = 1000L * 60 * 60;
public static Date addMinutes(Date d, int amount) {
return addMillis(d, MILLISECONDS_IN_A_MINUTE * amount);
}
// not visible from the outside
private static Date addMillis(Date d, long amount) {
return new Date(d.getTime() + amount);
}
It's not necessary, but there can be static methods and data members for internal use only.
An example for this is if you want an unique id for every instance of the class:
class Foo
{
private static int nextId = 0;
private static int generateId() { return ++nextId; }
private int id;
public Foo()
{
id = generateId();
}
}
As you can see, nextId and generateId() are not needed outside the class, nor should they be used outside the class. The class itself is responsible for generating id's. But you need them to be static (well, you need nextId to be static, but you can also make generateId() static since it doesn't access non-static members).
Whenever an object Foo is created, the static counter is incremented, thus you get different ids for each instance of the class. (this example is not thread-safe)
Suppose you have a static public method and this method must access to a private attribute. This private attribute must be static too. There's one reason why private static exists.
Example :
public class Test {
private static int myattr = 0;
public static void foo() {
myattr = 2;
}
}
Above, myattr must be a static attribute in order to use it in the foo() method.
Yes it is needed.
If you have a Static Method and want to use a private variables in that method, then you need to declare it static too.
Or you want the static variables not be visible to other packages, then don't declare it public.
From what I remember, it's not really needed. But public means, basically in any programming language, that it can be used by outside files. With private it can only be used within that file, and static means you cannot change the value of said reference. Whether these be functions, or variables, the same rules apply. I might be off. Haven't done Java in about a year and a half.
The ways you can incorporate these types is up to you. After all, a program is only as diverse as it's user. ^_^
Public and private keywoards have to do with visibility: which members do you want to accessible to other classes and which should be hidden or encapsulated.
Static members relate to the class as a whole, while non-static members operate on object instances.
I'm learning Java and I just wonder why public and private is used when a method or members is static?
I believe your question is due to a common misconception that the access modifiers are for instances, but they're not!
Two different instances can access each others private members if they are of the same class.
In other words, the access modifiers works on class level. Since also static members belong to some class, it makes sense to have access modifiers also on them.
A static method (or variable) that should only be used by code in the same class (as in the example by JB Nizet) should be private, while a static method or variable that may be used by code in any class should be public.
When the static is used with methods it doesn't only mean that it should be used by the members of other classes.
The case when we access the static methods of a class is one when
the class (which contains the method) cannot be instantiated i.e. no objects can be created of that class.
There may be situations when two different classes may have static methods with same name. In that case you want to use the method of the same class not the method of other class.
Related
I seen this bit of code, Even though I think I got the concept of static in Java I am bit confused. Can any one explain it to me, how an object being static works?
My code:
package com.oracle.certification.sampleTest;
public class Person {
static class Mail {
static String desc="Male";
}
static Gender Mail=new Gender();
}
package com.oracle.certification.sampleTest;
public class Gender {
String desc="Gender";
}
package com.oracle.certification.sampleTest;
public class Human {
public static void main(String str[]) {
System.out.println(Person.Mail.desc);
}
}
When the class Human is run, the O/P is 'gender' not 'male', even though des= gender is nonstatic and des=male is static with static inner class. Also I don't need to import the classes in Hman? I am sorry that I have very little knowledge about inner classes, first of all.
Can any one explain it to me, How an object being static works?
Essentially, static in that context means that the entity in question is attached to the class itself, not to an object of the class. Hence, with static there is exactly one instance of what you declare:
class T {
public static int staticMember = 0; // one variable stored in memory
public int nonStaticMember = 0; // as many variables stored in memory as objects are created from the class
}
See also What does the 'static' keyword do in a class?
However, your question is not necessarily a misunderstanding of static classes, but a corner case of name resolution: You are declaring both a type and a member variable with the same name (Mail) in one scope (within the Person class) - while one might think that this should not even be possible, the Java language does allow this and defines a couple of rules to determine which one to use.
From the JLS:
A simple name may occur in contexts where it may potentially be interpreted as the name of a variable, a type, or a package. In these situations, the rules of ยง6.5 specify that a variable will be chosen in preference to a type.
...
static class Mail { // a Type
}
static Gender Mail ... // a Variable with the same name
// - the compiler chooses to use this one
...
Hence, when referencing Person.Mail, the compiler chooses the variable, not the type (the inner class).
This question already has answers here:
Why can I access a private variable from main method?
(7 answers)
Closed 8 years ago.
I recently see a question that what is the execution result of this code below.
public class Sandys {
private int court;
public static void main(String argv[]){
Sandys s = new Sandys(99);
System.out.println(s.court);
}
Sandys(int ballcount){
court = ballcount;
}
}
I think it can't be executed because in main i try to access a private variable.
However, this code can be perfectly executed, and the result is 99. So I am confused, why the private variable can be accessed in this code? Though the main is in Sandys class, however i create a new Sandys. Can I still access the private variable of the new Sandys object in main?
You can access private members from inside the same class, even in static methods.
main() is a special method because it is used as a starting point for java application. However, it is still a normal static method and it follows all access restrictions of static methods. Is this main() a class method? Yes, it is. Hence, it can access private members of the same class.
Consider this: if there was no access to private fields factory methods would have to be written differently.
class A {
private int a=0;
private int b=0;
private A() {}
//getters
public static A getNewInstance(int a, int b) {
A a = new A();
a.a = a;
a.b = b;
return A;
}
It does make sense, doesn't it?
You can access ALL private, protected, public and not modifier variables inside class, but you can not access private variable from another class.
P.S. It is truth also for C#, C++ and many other programming languages.
A class is defined to some particular job and in that way it may use some variables that it don't want others to access it("others" means outsider classes) and some you want other classes to access it.It all depends on your requirement.
"Private instance variables are defined to be used in only with in the class".and since in your code you are trying to access the private instance variable inside the class itself then it is perfectly legal.
Note: A static method cannot access the instance variables if u want specify the instance i mean create the instance(object) inside of the static method and access it through the created reference.
Hi i have a web service in java, in which i have a class that has different methods that modify the string that the client sends and return it back according to the type of sting he wants. So based on the string type requirement a method is called..
like
class Test{
public static String a(String z)
{
// do stuff and return;
}
public static String b(String z)
{
// do stuff and return;
}
}
so if an array of like 10000 requests comes, these methods are called 10000 times, i want to know that should these methods be taken as static or NOT(i should create a global object of this class in my main web service class and call these methods) ?
I don't think you need to make method as static, if you can access the method within the object then you should (avoid static as much as possible).This improve code performance (in terms of memory utilization).
What's the compelling reason that these methods be static? If you need static methods, then create those. Otherwise, from a design standpoint, stick to non-static methods. You can't override static methods (though you can hide 'em.)
And there's this:
In Java, is there any disadvantage to static methods on a class?
You can use a static method if the method behaves the same for all cases. If the methods just does some work on the string supplied as a parameter and the behavior is the same for all instances, you can.
Again, you can also make a singleton out of it & call the methods through the UNIQUE_INSTANCE.
Something like:
public class Test {
private static final Test UNIQUE_INSTANCE = new Test();
private Test() {
}
public static final Test getUniqueInstance() {
return UNIQUE_INSTANCE;
}
public final String a(String z) {
// do stuff and return;
}
public final String b(String z) {
// do stuff and return;
}
}
Then you can do >>
Test.getUniqueInstance().a("Hello");
Test.getUniqueInstance().b("World");
If there is not any resource which is shared among the threads then there is not harm to use any static method.
Yes, there should be a Static modifier since there is no interaction between the different methods or functions, and the result is returned in the very same method. the "Static" word is to define a class variable or method that can be accessed without instantiating an object of such class.
if you do not intend to instantiate the class, and just need to use the methods inside, "Static" is the correct way to go, and set the class constructor to private.
let's assume we have the following code:
public class TestScope {
private int a = 1;
public static void main(String[] args) {
TestScope ts = new TestScope();
ts.a = 6;
System.out.println(ts.a);
}
}
Why at line: ts.a = 6; I can get access to private variable a?
I thought that private memebers cannot be accessed outside. I don't underestend this example.
Static methods are still considered part of the class they're declared in, and thus have access to private methods/fields.
If you had the main method (or any other static or instance method) in another class, you would indeed not be able to access a.
It's because a and main(String[]) are both part of the definition of the class TestScope
Private means that a variable or method can only be accessed inside the class definition. The fact that a is an instance variable doesn't mean it can't be accessed by a static public method in the same class.
If the public static void main(String[]) was inside a different class, then it would not be able to access ts's a, because a is hidden from other classes.
A static method is considered 'part' of the class it's in and so has private-scope access to instances of it. This same question was tackled here a couple days ago.
Right now I'm thinking about adding a private constructor to a class that only holds some String constants.
public class MyStrings {
// I want to add this:
private MyString() {}
public static final String ONE = "something";
public static final String TWO = "another";
...
}
Is there any performance or memory overhead if I add a private constructor to this class to prevent someone to instantiate it?
Do you think it's necessary at all or that private constructors for this purpose are a waste of time and code clutter?
UPDATE
I'm going for a final class with private constructor and a descriptive javadoc for the class. I can't use a ENUM (which I'd prefer) because I'm stuck on Java 1.4 for now. This would be my modification:
/**
* Only for static access, do not instantiate this class.
*/
public final class MyStrings {
private MyString() {}
public static final String ONE = "something";
public static final String TWO = "another";
...
}
Use of private constructor to prevent instantiation of class?
There are several ways you can think of users preventing from the Instantiations for the purpose of creating the Constants
As you have mentioned a class with the private Constructors and has all the string constants, is one way, even there is an overhead, that can be negligible
Else you can create a Class with Final Modifier and Define your string constants
You can use the Abstract Class with the String Constants
You can define the string constants in the properties files and can access from that, this will definitely reduce the memory and increase the flexibility of your code.
For me the best explanation is in Effective Java book: Item 4: Enforce noninstantiability with a private constructor (See more)
In Summary:
Private constructor is due utility classes were not designed to be instantiated, so is a design decision. (NO performance or memory overhead)
Making a class abstract doesn't work because can be subclassed and then instantiated.
With an abstract class the user may think the class is for inheritance.
The only way to ensure no instantiation is to add a private constructor which ensures the default constructor is not generated.
Private constructor prevents inheritance because the super constructor cannot be called (so it is not need the declare the class as final)
Throw an error in the private constructor avoids call it within the class.
Definetively, the best way would be something like next:
public class MyStrings {
private MyStrings () {
throw new AssertionError();
}
...
}
You could add a private constructor, but there are two other options.
In the same situation I would use an enumerator. If it makes sense to your implementation, you could use that instead, if it's public or private depends on where you need to use it:
public enum MyStrings {
ONE ("something"),
TWO ("something else");
private String value;
private MyStrings(String str) {
this.value = str;
}
}
Another option would be to put it in an abstract class, those can not be instantiated:
public abstract MyStrings {
public static final String STUFF = "stuff";
public static final String OTHER = "other stuff";
}
Access for both enumerator and abstract class works just like with the implementation you presented:
MyStrings.STUFF
If you don't won't anyone to make an object of the class you could make it abstract like this
public abstract class MyStrings {
public static final String ONE = "something";
public static final String TWO = "another";
}
and access your static variables like this
String val1 = MyStrings.ONE;
String val2 = MyStrings.TWO;
I think this would be a nicer solution.
I would rather use an enum to hold that Strings. This would ensure that wherever you use that Strings, you only get passed in one of the allowed Strings.
There is no performance or memory overhead if you add a private constructor in this case. As well, it is not needed since your public static variables are shared among all instances of your object.
If your class has only static members, then there is no need to have a private or public constructor. All members are accessible even without an object. In fact I find it confusing to have a constructor in such a case.
A synthetic public constructor would have been generated any way. So no.
Really a few bytes out of hundreds of millions at runtime isn't going to make much difference.
I also suggest making the class final and just for completeness have the constructor throw an exception.
If you want terse source code, you could create an enum with no values. Might cause some confusion with beginner programmers though.
That's the right way to store some constants, as also suggested in Effective Java (2nd Ed.), item 19.