Why can a "private" method be accessed from a different instance? - java

Although, this is a very basic code, it seems there is something fundamentally flawed in Java, or the JVM used by the Eclipse IDE I have used to run the code.
The code runs even though it should not (I think)! The code in A.java simply displays "Hello, I am A!"
Here it is:
import java.lang.*;
import java.util.*;
class A {
private void methodA() {System.out.println("Hello, I am A!");}
public static void main(String[] args) {
A a = new A();
a.methodA(); }
}
I do not understand why, after creating an instance of class A, main() succeeds in running a private method of class A on that instance. Yes, the main method belongs to class A, but it is not accessing the private method from inside the current object in the context of the "this" reference. In fact, since it is a static method, it cannot access non-static members from within the class. Instead of main(), a non-static member method could have invoked methodA() from inside only. But that is another issue since I have not defined any non-static second method.
Now that the inside-view is talked about, let's come back to the point, the outside-view. As you can see, main() attempts to invoke methodA from outside the object and succeeds! Why isn't private getting treated as private?
I am pulling my hair....
Anyone, please reply...

Yes, the main method belongs to class A, but it is not accessing the private method from inside the current object in the context of the "this" reference.
That doesn't matter. That's just not the model of accessibility that Java uses. What's important is the class in which the code is written, not whether it's accessing members in the same object.
This is very useful, as otherwise (for example) it would be impossible to implement an equals method using private members of both classes.
This may not be how you would have chosen to specify the language, but it is how Java is specified. See JLS 6.6.1 for details of accessibility. In particular:
Otherwise, if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.
Note that protected access is slightly odd here - a protected instance member of class SuperClass can only be accessed within code in SubClass via an expression of either SubClass or a further subclass. But it still doesn't have to be "the same" object.

private modifer
Methods, Variables and Constructors that are declared private can only be accessed within the declared class itself.

private means "private to the class". Not "private to the instance".
That's what allows implementing things like static factory methods calling private constructors, or equals() or compareTo() methods comparing private fields of objects of the same class, or copy constructors, etc.
Private members of enclosing classes are also accessible from inner classes of this enclosing class, and vice-versa.

After the technically correct answers here's my two cents why I think it is quite reasonable to implement private that way:
As I see it the main reason that private methods and attributes exists is "implementation hiding". You are declaring "Don't use this method from outside my class(!), since it might change or disapear anytime I like". So it makes sense to disallow access from outside the class. But if I'm accessing it from another object of the same class I and make any implementation changes I'm well aware of the changes and the accesses of the private members and can act accordingly.
Another thing to think about:
If class B extends class A, then any B-object also is an A-object, but it can't access the private A-methods. Why would that be if private methods were private to the object?

Related

Why have public methods inside private classes?

I was going through a part of a code which was something like this
// compare points according to their polar radius
public static final Comparator<Point2D> R_ORDER = new ROrder();
.
.
.
private static class ROrder implements Comparator<Point2D> {
public int compare(Point2D p, Point2D q) {
double delta = (p.x*p.x + p.y*p.y) - (q.x*q.x + q.y*q.y);
if (delta < 0) return -1;
if (delta > 0) return +1;
return 0;
}
}
Why do we have such public methods inside private static classes. What harm would it do if i made ROrder
Non-Static
Public
ROrder Non-Static
By making it non-static you will need the instance of the container class to create the instance of ROder, which maybe due to the design of the class would not make logic. You should keep class non-static only when you really need the instance of outer class to get the instance of inner class.
ROrder Public
Again because they wanted to restrict the use of ROrder outside the context of this class. They did not want any client code or other code to freely create instances of ROrder, as they would not be of any use.
Why do we have such public methods inside private static classes.
In this case because you are implementing an interface Comparator and you will pass this comparator for other uses, such as sorting and you would want the Collections class to have the visibility of compare method, so the method has to be public even if the class implementing the interface is private.
So this is just a logical way to enhance the readability and intent of use of the code.
Logical Use
This class wants the string to be in some format.
public class SomeClass{
private static class StringHelper{
//will do the task of parsing and validating that string object
}
}
Now in this case you would not want to keep StringHelper class public, as its use is too localized to be reused. So you would rather emphasize that by keeping it private. And there can be methods that are public if StringHelper implemented some interface.
UPDATE:
You should keep class non-static only when you really need the
instance of outer class to get the instance of inner class.
On that I think the answer can be too broad, but I would try to explain in short. By that what I mean was that if the inner class object shares some state of the outer object on which its processing is dependent, then you will need the object of outer class to share its state with the inner class object, but if the inner class instance is independent of the state of outer class, then it is safe to keep the inner class static.
This class implements Comparator and so must implement its methods. The implementation methods can't be static. Also, since interface methods are implicitly public, they must be declared public, regardless of the containing class's visibility. Try not doing so and it will fail to compile. This is certainly the reason it is declared public here -- it can't not be.
This is true regardless of whether the containing class is static or public. Here, it could be either of those things and the method inside would still have to be public and non-static.
Other methods that don't implement an interface could be private, and, logically probably should inside a private class as there would be no point in declaring it otherwise -- but it would be allowed by Java syntax.
All private members (fields, classes, whatever) are only visible inside the class. So, it doesn't matter what visibility you give a method of a private class - all methods will only be visible inside the containing class, because the class itself is private.
If the inner class implements an interface or extends a class, overridden methods may not have less visibility than the declaration in the super type, so that's one reason to have public methods in a private inner class.
However, although the syntax allows private classes to have public methods, it won't increase the visibility of those methods sufficiently to be visible outside the containing class. There are several examples in java of modifiers being legal but having no effect, such as inner interfaces being implicitly static (whether or not the static keyword is used).
This class is private because developer did not want to ROrder be instantiated in other place. But an instance can be accessed through the constant R_ORDER from other classes.
The method is public for two reason : first, compare is defined in the Comparator interface. Second, as R_ORDER is accessible from other classes, it is more than convenient to be able to call a method on this object. In this case, it is compare.
Finally, if the class was not static, it would keep a reference to the parent class, which is almost always not needed

Constraint on static

static methods can call only static methods/fields from same class. Questions:
Why non static methods/fields shall not be made available to static because once static method has been called then JVM has created an object for it, which can access other parts of class if JVM allows?
Why does static methods allow objects from non static methods of other classes. Imposing restriction that they can access only static of other classes and letting a static access non static members of same class will cause any difference?
Following is the java language specification for the static methods and fields. Hope it will help you
8.3.1.1. static Fields
If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized (§12.4).
A field that is not declared static (sometimes called a non-static field) is called an instance variable. Whenever a new instance of a class is created (§12.5), a new variable associated with that instance is created for every instance variable declared in that class or any of its superclasses.
8.4.3.2. static Methods
A method that is declared static is called a class method.
It is a compile-time error to use the name of a type parameter of any surrounding declaration in the header or body of a class method.
A class method is always invoked without reference to a particular object. It is a compile-time error to attempt to reference the current object using the keyword this (§15.8.3) or the keyword super (§15.11.2).
A method that is not declared static is called an instance method, and sometimes called a non-static method.
An instance method is always invoked with respect to an object, which becomes the current object to which the keywords this and super refer during execution of the method body.
A non-static method has an implicit this object to can call on other non-static methods
A static method cannot implicitly call a non-static method as it has no object to implicitly use. There is nothing to stop you explicitly using an object to call a method.
e.g.
class Main {
public static void main(String... ignored) {
new Main().nonstatic(); // calls non-static method
}
public void nonstatic() {
nonstatic2(); // calls non-static object with implicit reference to "this"
}
public void nonstatic2() {
staticMethod(this);
}
public static void staticMethod(Main main) {
main.nonstatic3(); // static calls non-static with explicit object.
}
public void nonstatic3() {
}
static methods can call only static methods/fields from same class.
This is not true as the example shows.
Why non static methods/fields shall not be made available to static because once static method has been called then JVM has created an object for it,
The JVM could create an object automagically, but this is unlikely to be useful, esp if the object has no default constructor.
which can access other parts of class if JVM allows?
It could allow, but shouldn't IMHO as this would be more confusing than useful.
Why does static methods allow objects from non static methods of other classes.
static methods allow objects from all classes, not just other ones.
Imposing restriction that they can access only static of other classes and letting a static access non static members of same class will cause any difference?
The difference is you don't have an implicit instance of the class This is the whole point of a static method.
If you wanted an implicit instance, you would use a non-static method.
once Static method has been called than JVM has created an object for
it
This is not true. Static methods can be called without creating an object of that class defining static method (remember public static void main()).
Why does Static methods() allow objects from nonstatic methods of
other classes.
This is because other classe instance can exist irrespective of whether object of class defining static method (which access the the other class) exists.
Checkout this link for further insights.
In order to understand why static methods cannot call non static methods or access non static variables you need to understand the diffeerence between a class and an object.
Java is an object oriented language. First you define a class which holds the state(instance variables) and methods which change the state(instance variables).
But class is not an object. It is just a template for object creation, for which you use the new keyword (creating an instance of class).
Once you create an object its variables are in an inital state, and then you call methods which read or change object's state. Such variables and methods are non static in the sense that they require an object instance of a class.
However, in a class you can define a method that does not read or change the state. Method's behavior is not dependent at all on instance variables.
Such method can be declared static, which means no instance of the class is required to run the method.
You call a static method directly on a class ( without a reference to an object ):
MyClass.staticMethod();//will not read or change any state, because there is no object here
You can also call a static method on an object but will not access object's state, because its behavior does not depend nor does not change object's state. Call to obj.staticMethod(); is the same as MyClass.staticMethod();:
//Create an instance of a MyClass
MyClass obj = new MyClass();
//will not read or change any state of obj.
obj.staticMethod();
Note however that static methods are not completely stateless, they can still read or change the state of static varibables.
Note also that in Java you cannot override static methods(unlike in Delphi) - don't declare a method as static if you think subclasses will need to override it.
Therefore as rule-of-thumb declare static methods in special purpose utility classes which don't need an instance anyway, like for example java.lang.Math, otherwise
don't declare a method as static even if it doesn't read or change object's state because you might need to override it later.
Why non static methods/fields shall not be made available to static because once static method has been called then JVM has created an object for it, which can access other parts of class if JVM allows?
If static methods were allowed to access non-static methods, that would mean, an instance level method would be called without an instance of the class. Then how will you override the method?. Overriding looks at the object to call/invoke the method and if you directly call non-static (instance) methods from static methods, which object is being used to call?.
And from a design perspective -
Assume you have a class called Dog.
Every dog eats, sleeps etc . But the most important thing to remember is all these things are specific to the Dog instance. and state of each object should be accessed via instance level methods - thats the whole point of encapsulation. If you say Dog.sleep(). Which dog should sleep?

Why can't constructors be final, static, or abstract?

Why can't constructors be final, static, or abstract in Java?
For instance, can you explain to me why this is not valid?
public class K {
abstract public K() {
// ...
}
}
When you set a method as final it means: "I don't want any class override it." But according to the Java Language Specification:
JLS 8.8 - "Constructor declarations are not members. They are never inherited and therefore are not subject to hiding or overriding."
When you set a method as abstract it means: "This method doesn't have a body and it should be implemented in a child class." But the constructor is called implicitly when the new keyword is used so it can't lack a body.
When you set a method as static it means: "This method belongs to the class, not a particular object." But the constructor is implicitly called to initialize an object, so there is no purpose in having a static constructor.
The question really is why you want constructor to be static or abstract or final.
Constructors aren't inherited so can't be overridden so whats the use
to have final constructor
Constructor is called automatically when an instance of the class is
created, it has access to instance fields of the class. What will be
the use of a static constructor.
Constructor can't be overridden so what will you do with an abstract
constructor.
A Java constructor is implicitly final, the static / non-static aspects of its semantics are implicit1, and it is meaningless for a Java constructor to be abstract.
This means that the final and static modifiers would be redundant, and the abstract keyword would have no meaning at all.
Naturally, the Java designers didn't see in any point in allowing redundant and/or meaningless access modifiers on constructors ... so these are not allowed by the Java grammar.
Aside: It is a shame that they didn't make the same design call for interface methods where the public and abstract modifiers are also redundant, but allowed anyway. Perhaps there is some (ancient) historical reason for this. But either way, it cannot be fixed without rendering (probably) millions of existing Java programs uncompilable.
1 - Actually, constructors have a mixture of static and non-static semantics. You can't "call" a constructor on an instance, and it they are not inherited, or overridable. This is similar to the way static methods work. On the other hand, the body of a constructor can refer to this, and call instance methods ... like an instance method. And then there is constructor chaining, which is unique to constructors. But the real point is that these semantics are fixed, and there is no point allowing a redundant and probably confusing static modifier.
public constructor: Objects can be created anywhere.
default constructor: Objects can be created only in the same package.
protected constructor: Objects can be created by classes outside the package only if it's a subclass.
private constructor: Object can only be created inside the class (e.g., when implementing a singleton).
The static, final and abstract keywords are not meaningful for a constructor because:
static members belong to a class, but the constructor is needed to create an object.
An abstract class is a partially implemented class, which contains abstract methods to be implemented in child class.
final restricts modification: variables become constant, methods can't be overridden, and classes can't be inherited.
Final: Because you can't overwrite/extend a constructor anyway. You can extend a class (to prevent that you make it final) or overwrite a method (to prevent that you make it final), but there is nothing like this for constructors.
Static: If you look at the execution a constructor is not static (it can access instance fields), if you look at the caller side it is (kind of) static (you call it without having an instance. Its hard to imagine a constructor being completely static or not static and without having a semantic separation between those two things it doesn't make sense to distinguish them with a modifier.
Abstract: Abstract makes only sense in the presence of overwriting/extension, so the same argument as for 'final' applies
No Constructors can NEVER be declared as final. Your compiler will always give an error of the type "modifier final not allowed"
Final, when applied to methods, means that the method cannot be overridden in a subclass.
Constructors are NOT ordinary methods. (different rules apply)
Additionally, Constructors are NEVER inherited. So there is NO SENSE in declaring it final.
Constructors are NOT ordinary methods. (different rules apply)
Additionally, Constructors are NEVER inherited. So there is NO SENSE in declaring it final.
No Constructors can NEVER be declared final. YOur compiler will always give an error of the type "modifer final not allowed"
Check the JLS Section 8.8.3 (The JLS & API docs should be some of your primary sources of information).
JLS section 8 mentions this.
Constructors (§8.8) are similar to methods, but cannot be invoked
directly by a method call; they are used to initialize new class
instances. Like methods, they may be overloaded (§8.8.8).
But constructors per say are not regular methods. They can't be compared as such.
why constructor can not be static and final are well defined in above answers.
Abstract: "Abstract" means no implementation . and it can only be implemented via inheritance. So when we extends some class, all of parent class members are inherited in sub-class(child class) except "Constructor". So, lets suppose, you some how manage to declare constructor "Abstract", than how can you give its implementation in sub class, when constructor does not get inherit in child-class?
that's why constructor can't be
abstract .
lets see first
final public K(){
*above the modifier final is restrict 'cause if it final then some situation where in some other class or same class only we will override it so thats not gonna happen here proximately not final
eg:
we want public void(int i,String name){
//this code not allowed
let static,, static itz all about class level but we create the object based constructor by using 'new' keyword so,,,,,, thatsall
abstract itz worst about here not at 'cause not have any abstract method or any declared method
Unfortunately in PHP the compiler does not raise any issue for both abstract and final constructor.
<?php
abstract class AbstractClass
{
public abstract function __construct();
}
class NormalClass
{
public final function __construct() {
echo "Final constructor in a normal class!";
}
}
In PHP static constructor is not allowed and will raise fatal exception.
Here in AbstractClass obviously a constructor either can be declared as abstract plus not implemented or it can be declared as something among (final, public, private, protected) plus a function body.
Some other related facts on PHP:
In PHP having multiple constructor __construct() is not possible.
In PHP a constructor __construct() can be declared as abstract, final, public, private and protected!
This code was tested and stood true for in PHP versions from 5.6 up to 7.4!

Why can other methods be "static" but a constructor cannot?

I do not understand why the main method has to be static. I understand static variables but static methods are difficult for me to grasp. Do static method exists so that one can create two methods with the same name in two different classes that won't clash with each other?
Also, I don't understand why I can't create a static constructor.
Could anyone help explain this concept?
Java has [static constructors] static initialization blocks which can be viewed as a "static constructor":
class Foo {
static String Bar;
static {
// "static constructor"
Bar = "Hello world!";
}
}
In any case, the only method in the main class which must be static is the main method. This is because it is invoked without first creating an instance of the "main class". A common technique, and the one I prefer, is to quickly get out of static context:
class Main {
int argCount;
// constructor
public Main (String[] args) {
// and back to boring ol' non-static Java
argCount = args.length;
}
void runIt () {
System.out.println("arg count: " + argCount);
}
// must be static -- no Main instance created yet
public static void main (String[] args) {
Main me = new Main(args);
me.runIt();
}
}
Also, static has nothing to do with "name clashes". A static method (or variable) is simply a method (or variable) that is not associated with a specific instance of a type. I would recommend reading through the Classes and Objects Java Tutorial and the section Understanding Instance and Class Variables.
Happy coding.
I am sharing one of the reason "why not a java constructor be static".
Simply to say, "A java constructor is always non static" because,
The purpose of the constructor is only to initialize/construct the object, and to make inheritance possible. To do these we need to use the two useful java keywords (cum non-static variables) such as this and super.
We will use 'this' to initialize the object.
We/Java will use super(ofcourse super()) to invoke super class constructor so that super object(or Object class) created first then the child object(hence the inheritance)
If the constructor is static then we cant use that two keywords(non-static variables) inside the constructor(As we know non-static stuff cant be referenced from static context)
So java constructors should not static.
Static methods belong to a class, not an object. The main method must be static because it is called first, before any other code has executed to instantiate any objects. It provides an entry point to the program. Static methods are called from outside of the container of an object. The same is true of static class variables. Only one copy exists for the entire class, as opposed to a member variable, which is created once for each object created from a class. They are used to store data for the class, such as the number of object instances have been created and not destroyed. This data belongs with the class. A good example of a static method is in the singleton pattern, where the constructor is private and can only be accessed by a static member function. A function outside the class would be unable to replicate this functionality. This method acts on class data and objects, so logically belongs to the same class. This all boils down to encapsulation. A class is responsible only for itself and knows only itself.
On the other hand, object methods are meant to operate on the data associated with a single instance of a class, an object. Constructors are the code that is used to initialize an object and set it's data to an initial state. They are executed immediately (and automatically) after the memory has been allocated to store a new object. Even if you do not explicitly define a constructor, a kind of "default constructor" is executed in order to map the object's member variables and the object's method code to the new object.
Hope this helps.
Constructor is used to create Objects.
Static is generally which is same for all objects.
So, if we have had static constructors creation of one object would affect all the other existing objects.
Static methods only reference to static variables. Therefore all the initial parameters which you are giving to create an object would change for all objects. It is no point creating similar objects for no use.
Hope this helps.... :)
Constructor is the property of an object while static has nothing to do with object. That's why there is nothing like static constructor. But we have static block to do the similar task as constructor i.e. initialization of fields etc.
On page 272 of Thinking In Java, 4th Edition, by Bruce Eckel, it says:
²The constructor is also a static method even though the static keyword is not explicit. So to be precise, a class is first loaded when any of its static members is accessed.
A little bit more context.
... the compiled code for each class exists in its own separate file. That file isn't loaded until the code is needed. In general you can say "class code is loaded at the point of first use." This is usually when the first object of that class is constructed, but loading also occurs when a static field or static method is accessed.²
This makes a lot of sense, if you think about the rule that says that a static method can't use non-static methods of the same class. I had this doubt a couple weeks ago when I couldn't understand how, using the Singleton Pattern, you could access the constructor inside the static method that is used to create a new instance of that class. Today I was flipping through the book and I came across this explanation.
It also makes sense in a way that, if the constructor wasn't static, you'd first need an instance of that class to be able to access it, but I guess this could spark up the old discussion about the chicken or the egg.
Hope it helped!
Constructors are neither entirely static (class level) or entirely non-static (instance level).
Unlike instance methods, constructors are not inherited.
Unlike static methods, a constructor can refer to this.
So, why can't you declare a constructor static?
Well, my take is that a (redundant) static keyword would be confusing and would not serve any purpose. Therefore they decided not to allow it.
The explanation that static initialization blocks can be viewed as constructors is (IMO) conceptually wrong. (It is analogous to saying that an instance initialization block is a regular constructor. Which is equally wrong.)
The key distinctions between static initialization and construction1 are:
static initialization happens at an indeterminate time2; there is no equivalent to new for class initialization,
there is no straight-forward way to pass (constructor) parameters to the initialization code
there is no practical way to recover from errors occurring during static initialization.
1 - Hypothetically, if class initialization was explicit, then it would make sense to have static constructors. But the downsize would be that applications would need to explicitly "construct" all of the classes that they used ... which would be horrible.
2 - You have a degree of control if you load a class dynamically, but even then if the class has already been loaded and initialized in the current classloader, then attempting to control initialization will fail.
I do not understand why the main method has to be static.
It has to be if you want the main method to act as an entrypoint for your application.
The problem is that if main was an instance method, then there would need to be an instance of your entrypoint class to call the main method on. But how do you create it? Which constructor would you choose? What if there was no public constructor?
The bottom line is that this is the way that Java was designed ... back in the 1990's ... and so far they have not seen the need to change this.
a) static is belongs to class not object and constrictor is called during the object creation.
b) if we create a constructor as static then it can't be call by subclass as static is accessible only from class not by sub class. So during subclass object creation it can't be call the present class constructor.
c) static members are executed first in the program, so if we declare constructor as static then it will executed before object creation which is oppose the purpose of the constructor.
If we declare constructor as static then it will give compile time error.
If we want to initialize static member then need to use of static block.
I wrote a simple example as an answer to a related question yesterday which may help make things more understandable: what's the point of java constructor?
The point of Static methods is that they can be called without creating an instance of a class, while "normal" instance methods are related to an instance, and can not be called without one.
Since the Main method of the Main class is the entry point of the program, no instance can possibly have been created yet, so naturally, you can not access it via an instance. Therefore, it is Static, so it can be run as the start of the program.
Just take a look on this link, it will definately help you to understand:
Why can't make a constructor static?
AND
Constructor is called at Run-time when we create Objects.
Static is same for all objects but all objects have their own state and properties.
So, if we have had static constructors creation of one object would affect all the other existing objects.
Note: static is class level while constructors related to the objects.
e.g.
public class Foo
{
String name;
int id;
// define constructors
Foo (String name, int id)
{
this.name = name;
this.id = id;
}
p s v m(String[] arg)
{
Foo f1 = new Foo("Amit",001);
Foo f2 = new Foo("Rahul",002);
}
}
If we create static constructor then both objects(f1 also) will contain the last updated value regarding name and id as Rahul and 002.
A constructor cannot be static, because in an OO language, the process for creating an object is as follows:
allocate the object
call the constructor to initialise the newly-allocated object
Constructors are not used anywhere else (and a type-safe language should enforce this), so it follows that a constructor will always be called in a non-static context.
If a constructor were static, it would not receive a reference to the newly-allocated object, and thus would not be able to initialise it.
Thus, a constructor can always be non-static (as it is always called from a non-static context) and must always be non-static (otherwise it would be unable to perform its task).
The main(String[]) method has a specific prototype that is dictated by how the Java runtime environment works. When you invoke java MyApplication from the command line, the Java VM will look for a static main(String[]) method contained in that class in order to execute the application. If that method is not found, then the Java VM can't run the class as an application. That's just how the language is defined. It also means that the Java VM doesn't create an instance of your application class in order to run it.
Now, if you want your class to be usable either as a standalone application or as an instance that's created by something else, then you can have your class implement the Runnable interface, and also provide a main method that executes the run method on a new instance.
public class MyRunnableThing implements Runnable
{
// Define whatever variables your runnable thing needs here as
// private instance fields.
/** Fulfills requirements of Runnable interface. */
public void run()
{
System.out.println( "I'm running..." ) ;
}
/** Also makes the class runnable from the console. */
public static void main( String[] args )
{
MyRunnableThing runMeNow = new MyRunnableThing() ;
runMeNow.run() ;
}
}
Now any class could potentially create an instance of MyRunnableThing and use its run() method to produce the same behavior that would have been seen by executing java MyRunnablething.
See also: Working with Static Constructor in Java. Some highlights from that Q&A:
A constructor is used to create an instance of the class, so it's an instance method, not a static method.
You can create a static method that creates an instance of the class, using the constructor. This is how the trendy new "builder" classes work.
You can create a static method that returns a persistent, unique singleton instance.
If your class has static members, then you can create a static initializer to initialize the values of those members.
The purpose of Constructor is to Construct an Object i.e. to initialize class's instance variables either their default values or by their initialized values. non-static Instance variables can't be accessed by static methods . So constructor is not static.
The method declared as static requires no object creation .As we don't create object for the main method it is declared as static.
constructor is implicitly called to initialize an object, so there is no purpose in having a static constructor.
First, the key word static means that everything marked static must be the class-level thing and belongs to the class only.While constructors belong to object and they may usually be called when we use the new operator.So we now know that a constructor is not even a class property,how could we possibly mark it as static?
Second,static constructor violates the whole purpose of inheritance in java.Every time just before we create an subclass object ,JVM automatically calls the superclass constructor to make it ready for the subclass object to be created.But if we mark the constructor static,the subclass will not be able to access the constructor of its superclass because it's marked static thus belongs to class only.
Java does not permit to declare a constructor as static. Following are the reasons.
Static means for the same class. i.e, static methods cannot be inherited.
With static, "this" reference (keyword) cannot be used. "this" is always linked to an object. A constructor always belongs to some object.
If a constructor is static, an object of subclass cannot access. If static is allowed with constructor, it is accessible within the class but not by subclass.
Static Belongs to Class, Constructor to Object
We know that static methods, block or variables belong to the class. Whereas a Constructor belongs to the object and called when we use the new operator to create an instance. Since a constructor is not class property, it makes sense that it’s not allowed to be static.

When to use static methods

I am wondering when to use static methods? Say if I have a class with a few getters and setters, a method or two, and I want those methods only to be invokable on an instance object of the class. Does this mean I should use a static method?
Example:
Obj x = new Obj();
x.someMethod();
...or:
Obj.someMethod(); // Is this the static way?
I'm rather confused!
One rule-of-thumb: ask yourself "Does it make sense to call this method, even if no object has been constructed yet?" If so, it should definitely be static.
So in a class Car you might have a method:
double convertMpgToKpl(double mpg)
...which would be static, because one might want to know what 35mpg converts to, even if nobody has ever built a Car. But this method (which sets the efficiency of one particular Car):
void setMileage(double mpg)
...can't be static since it's inconceivable to call the method before any Car has been constructed.
(By the way, the converse isn't always true: you might sometimes have a method which involves two Car objects, and still want it to be static. E.g.:
Car theMoreEfficientOf(Car c1, Car c2)
Although this could be converted to a non-static version, some would argue that since there isn't a "privileged" choice of which Car is more important, you shouldn't force a caller to choose one Car as the object you'll invoke the method on. This situation accounts for a fairly small fraction of all static methods, though.
Define static methods in the following scenarios only:
If you are writing utility classes and they are not supposed to be changed.
If the method is not using any instance variable.
If any operation is not dependent on instance creation.
If there is some code that can easily be shared by all the instance methods, extract that code into a static method.
If you are sure that the definition of the method will never be changed or overridden. As static methods can not be overridden.
There are some valid reasons to use static methods:
Performance: if you want some code to be run, and don't want to instantiate an extra object to do so, shove it into a static method. The JVM also can optimize static methods a lot (I think I've once read James Gosling declaring that you don't need custom instructions in the JVM, since static methods will be just as fast, but couldn't find the source - thus it could be completely false). Yes, it is micro-optimization, and probably unneeded. And we programmers never do unneeded things just because they are cool, right?
Practicality: instead of calling new Util().method(arg), call Util.method(arg), or method(arg) with static imports. Easier, shorter.
Adding methods: you really wanted the class String to have a removeSpecialChars() instance method, but it's not there (and it shouldn't, since your project's special characters may be different from the other project's), and you can't add it (since Java is somewhat sane), so you create an utility class, and call removeSpecialChars(s) instead of s.removeSpecialChars(). Sweet.
Purity: taking some precautions, your static method will be a pure function, that is, the only thing it depends on is its parameters. Data in, data out. This is easier to read and debug, since you don't have inheritance quirks to worry about. You can do it with instance methods too, but the compiler will help you a little more with static methods (by not allowing references to instance attributes, overriding methods, etc.).
You'll also have to create a static method if you want to make a singleton, but... don't. I mean, think twice.
Now, more importantly, why you wouldn't want to create a static method? Basically, polymorphism goes out of the window. You'll not be able to override the method, nor declare it in an interface (pre-Java 8). It takes a lot of flexibility out from your design. Also, if you need state, you'll end up with lots of concurrency bugs and/or bottlenecks if you are not careful.
After reading Misko's articles I believe that static methods are bad from a testing point of view. You should have factories instead(maybe using a dependency injection tool like Guice).
how do I ensure that I only have one of something
only have one of something
The problem of “how do I ensure that I
only have one of something” is nicely
sidestepped. You instantiate only a
single ApplicationFactory in your
main, and as a result, you only
instantiate a single instance of all
of your singletons.
The basic issue with static methods is they are procedural code
The basic issue with static methods is
they are procedural code. I have no
idea how to unit-test procedural code.
Unit-testing assumes that I can
instantiate a piece of my application
in isolation. During the instantiation
I wire the dependencies with
mocks/friendlies which replace the
real dependencies. With procedural
programing there is nothing to "wire"
since there are no objects, the code
and data are separate.
A static method is one type of method which doesn't need any object to be initialized for it to be called. Have you noticed static is used in the main function in Java? Program execution begins from there without an object being created.
Consider the following example:
class Languages
{
public static void main(String[] args)
{
display();
}
static void display()
{
System.out.println("Java is my favorite programming language.");
}
}
Static methods in java belong to the class (not an instance of it). They use no instance variables and will usually take input from the parameters, perform actions on it, then return some result. Instances methods are associated with objects and, as the name implies, can use instance variables.
No, static methods aren't associated with an instance; they belong to the class. Static methods are your second example; instance methods are the first.
If you apply static keyword with any method, it is known as static method.
A static method belongs to the class rather than object of a class.
A static method invoked without the need for creating an instance of a class.
static method can access static data member and can change the value of it.
A static method can be accessed just using the name of a class dot static name . . . example : Student9.change();
If you want to use non-static fields of a class, you must use a non-static method.
//Program of changing the common property of all objects(static field).
class Student9{
int rollno;
String name;
static String college = "ITS";
static void change(){
college = "BBDIT";
}
Student9(int r, String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student9.change();
Student9 s1 = new Student9 (111,"Indian");
Student9 s2 = new Student9 (222,"American");
Student9 s3 = new Student9 (333,"China");
s1.display();
s2.display();
s3.display();
} }
O/P: 111 Indian BBDIT
222 American BBDIT
333 China BBDIT
Static methods are not associated with an instance, so they can not access any non-static fields in the class.
You would use a static method if the method does not use any fields (or only static fields) of a class.
If any non-static fields of a class are used you must use a non-static method.
Static methods should be called on the Class, Instance methods should be called on the Instances of the Class. But what does that mean in reality? Here is a useful example:
A car class might have an instance method called Accelerate(). You can only Accelerate a car, if the car actually exists (has been constructed) and therefore this would be an instance method.
A car class might also have a count method called GetCarCount(). This would return the total number of cars created (or constructed). If no cars have been constructed, this method would return 0, but it should still be able to be called, and therefore it would have to be a static method.
Use a static method when you want to be able to access the method without an instance of the class.
Actually, we use static properties and methods in a class, when we want to use some part of our program should exists there until our program is running. And we know that, to manipulate static properties, we need static methods as they are not a part of instance variable. And without static methods, to manipulate static properties is time consuming.
Static:
Obj.someMethod
Use static when you want to provide class level access to a method, i.e. where the method should be callable without an instance of the class.
Static methods don't need to be invoked on the object and that is when you use it. Example: your Main() is a static and you don't create an object to call it.
Static methods and variables are controlled version of 'Global' functions and variables in Java. In which methods can be accessed as classname.methodName() or classInstanceName.methodName(), i.e. static methods and variables can be accessed using class name as well as instances of the class.
Class can't be declared as static(because it makes no sense. if a class is declared public, it can be accessed from anywhere), inner classes can be declared static.
Static methods can be used if
One does not want to perform an action on an instance (utility methods)
As mentioned in few of above answers in this post, converting miles to kilometers, or calculating temperature from Fahrenheit to Celsius and vice-versa. With these examples using static method, it does not need to instantiate whole new object in heap memory. Consider below
1. new ABCClass(double farenheit).convertFarenheitToCelcium()
2. ABCClass.convertFarenheitToCelcium(double farenheit)
the former creates a new class footprint for every method invoke, Performance, Practical. Examples are Math and Apache-Commons library StringUtils class below:
Math.random()
Math.sqrt(double)
Math.min(int, int)
StringUtils.isEmpty(String)
StringUtils.isBlank(String)
One wants to use as a simple function. Inputs are explictly passed, and getting the result data as return value. Inheritence, object instanciation does not come into picture. Concise, Readable.
NOTE:
Few folks argue against testability of static methods, but static methods can be tested too! With jMockit, one can mock static methods. Testability. Example below:
new MockUp<ClassName>() {
#Mock
public int doSomething(Input input1, Input input2){
return returnValue;
}
};
I found a nice description, when to use static methods:
There is no hard and fast, well written rules, to decide when to make a method static or not, But there are few observations based upon experience, which not only help to make a method static but also teaches when to use static method in Java. You should consider making a method static in Java :
If a method doesn't modify state of object, or not using any instance variables.
You want to call method without creating instance of that class.
A method is good candidate of being static, if it only work on arguments provided to it e.g. public int factorial(int number){}, this method only operate on number provided as argument.
Utility methods are also good candidate of being static e.g. StringUtils.isEmpty(String text), this a utility method to check if a String is empty or not.
If function of method will remain static across class hierarchy e.g. equals() method is not a good candidate of making static because every Class can redefine equality.
Source is here
Static methods are the methods in Java that can be called without creating an object of class. It is belong to the class.
We use static method when we no need to be invoked method using instance.
A static method has two main purposes:
For utility or helper methods that don't require any object state.
Since there is no need to access instance variables, having static
methods eliminates the need for the caller to instantiate the object
just to call the method.
For the state that is shared by all
instances of the class, like a counter. All instance must share the
same state. Methods that merely use that state should be static as
well.
You should use static methods whenever,
The code in the method is not dependent on instance creation and is
not using any instance variable.
A particular piece of code is to be shared by all the instance methods.
The definition of the method should not be changed or overridden.
you are writing utility classes that should not be changed.
https://www.tutorialspoint.com/When-to-use-static-methods-in-Java
In eclipse you can enable a warning which helps you detect potential static methods. (Above the highlighted line is another one I forgot to highlight)
I am wondering when to use static methods?
A common use for static methods is to access static fields.
But you can have static methods, without referencing static variables. Helper methods without referring static variable can be found in some java classes like java.lang.Math
public static int min(int a, int b) {
return (a <= b) ? a : b;
}
The other use case, I can think of these methods combined with synchronized method is implementation of class level locking in multi threaded environment.
Say if I have a class with a few getters and setters, a method or two, and I want those methods only to be invokable on an instance object of the class. Does this mean I should use a static method?
If you need to access method on an instance object of the class, your method should should be non static.
Oracle documentation page provides more details.
Not all combinations of instance and class variables and methods are allowed:
Instance methods can access instance variables and instance methods directly.
Instance methods can access class variables and class methods directly.
Class methods can access class variables and class methods directly.
Class methods cannot access instance variables or instance methods directly—they must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to.
Whenever you do not want to create an object to call a method in your code just declare that method as static. Since the static method does not need an instance to be called with but the catch here is not all static methods are called by JVM automatically. This privilege is enjoyed only by the main() "public static void main[String... args]" method in java because at Runtime this is the method Signature public "static" void main[] sought by JVM as an entry point to start execution of the code.
Example:
public class Demo
{
public static void main(String... args)
{
Demo d = new Demo();
System.out.println("This static method is executed by JVM");
//Now to call the static method Displ() you can use the below methods:
Displ(); //By method name itself
Demo.Displ(); //By using class name//Recommended
d.Displ(); //By using instance //Not recommended
}
public static void Displ()
{
System.out.println("This static method needs to be called explicitly");
}
}
Output:-
This static method is executed by JVM
This static method needs to be called explicitly
This static method needs to be called explicitly
This static method needs to be called explicitly
The only reasonable place to use static methods are probably Math functions, and of course main() must be static, and maybe small factory-methods. But logic should not be kept in static methods.

Categories