regarding static method in java - java

When studying the java programming language, I meet the following statement
I am confusing about the statement marked with yellow. Especially, what does instance method mean here? If there is an example to explain this point, then it would be much appreciated.

If I have a method:
public static void print(String line) {
System.out.println(line);
}
... and then remove the static keyword ...
public void print(String line) {
System.out.println(line);
}
... it is now an instance method, can no longer be invoked from the class, and must instead be invoked from an instance (hence the name).
e.g.,
MyClass.print(line);
vs.
new MyClass().print(line);
That's really it.

You can call static methods without needing to intantiate an object:
TestObject.staticMethodCall();
For non-static methods you need to create an instance to call a method on:
new TestObject().nonStaticMethodCall();

Consider following sequence.
Define Class X with static void foo() a static method
Define Class Y which calls X.foo() in its main method
Compile the two classes and (somehow) run it
Change X.foo() to be a instance method by removing the static qualifier
Compile only X, not Y
Run the Y class again and observe the error.
On the other hand, if you had changed the body of X.foo in certain ways without changing its static-ness then there would have been no error. For more, look up "binary compatibility"

First of all, you should understand the difference between the class method and the instance method. An example is shown below.
public Class Example{
public static void main(String[] args) {
Example.method1();//or you can use method1() directly here
Example A = new Example();
A.method2();
}
public static void method1(){
}
public void method2(){
}
}
method1 is the class method which you can take it as the method of the class. You can invoke it without initiating a object by new method. So you can invoke it in such way: Example.method1()
method2 is the instance method which requires you to invoke it by initiating the instance of an object, i.e. Example A = new Example(); A.method2();
Additional:
The error is due to the removal of the static modifier of an class method like method1. Then method1 becomes an instance method like method2 which you have to initiate an instance to call.

Related

Why make an object for Main class, for the methods to work?

I was facing an error before, but when I made an object in this class the and called for the method, it worked flawlessly. Any explanation? Do I always have to make an object to call for methods outside of the main method (but in the same class)?
here:
public class A{
public static void main(String[] args){
A myObj= new A();
System.out.println(myObj.lets(2));
}
public int lets(int x){
return x;
}
}
You need to understand static. It associates a method or field to the class itself (instead of a particular instance of a class). When the program starts executing the JVM doesn't instantiate an instance of A before calling main (because main is static and because there are no particular instances of A to use); this makes it a global and an entry point. To invoke lets you would need an A (as you found), or to make it static (and you could also limit its' visibility) in turn
private static int lets(int x) {
return x;
}
And then
System.out.println(lets(2));
is sufficient. We could also make it generic like
private static <T> T lets(T x) {
return x;
}
and then invoke it with any type (although the type must still override toString() for the result to be particularly useful when used with System.out.println).
There are a importance concept to consider an is static concept. In your example you have to create an instance of your class because the main method is static and it only "operate" with other statics methods or variable. Remember that when you instantiate a class you are creating a copy of that class an storing that copy in the instance variable, so as the copy (That was create inside of a static method in your case) is also static so it can access the method which is not static in that context.
In order to not create an instance and access to your method you need to make your lets method static(due to the explanation abode)
public static int lets(int x){
return x;
}
And in your main you don't need to instantiate the class to access to this method.
public static void main(String[] args){
System.out.println(lets(2));
}
Check this guide about static in java: https://www.baeldung.com/java-static
Hope this help!

new instance of the class in java main method

I am new to java, I was wondering why I need to create a new instance of the class to use its non-static methods in the main method but not in the other methods like the following
public class Test {
public void test(){
System.out.println("test");
}
public static void main(String args[]){
test(); // error Cannot make a static reference to the non-static method test() from the type Test
}
public void tst(){
test(); // no errors
}
}
Look, main is static method. You call it from the class which hasn't been initialized yet. You can do that, however you can't call Test#test without having an instance of Test.
Working code:
public class Test {
public void test(){
System.out.println("test");
}
public static void main(String args[]){
Test test = new Test();
test.test();
}
public void tst(){
test(); // no errors
}
}
Explanation:
Non-static methods must be called on objects. Objects are created with new keyword. Sometimes, there are methods which return new objects, but they call new inside.
Static methods can be called without creating an object. You then need to declare them static. How? Simply add static before return type.
Example of how static methods work:
public class Test {
public void test(){
System.out.println("test");
}
public static void main(String args[]){
tst();
Test test = new Test();
test.test();
}
public static void tst(){
Test test = new Test();
test.test();
}
}
There were no errors in tst() because you called the method which you saw from that scope. It means that if there was an object of class Test created, you could call tst and test. If you tried to call tst before my refactor, you would have been warned the same warning.
By definition
Static methods, belong to the class, meaning you can use them by calling
ClassName.methodName();
Instance methods (non-static) must be called on instances of an object of a certain class.
like
Test test = new Test();
test.test();
You can't call a non-static method from static area for this any how you have to create an object and through this object only you can call this method.
Or if you want to call directly the method from static area then make method also static.
Why?? Normally in java there are 3 types of variable based on our declare position 1) local variable 2) Instance variable and 3) static variable, same as instance method and static method also.
NOTE Static method or block execute at the time of class loading and that time you are trying to call a normal method and the scope of normal method is same as the scope of object so, without creating object u can't think also about a normal/instance method.
Think of static methods as existing outside of any instance of that class. It is really an instance-less method. In order to call non-static methods, you must reference an instance in order to invoke it.
Another way to look at the issue is from the point of view of the variables. Static variables are shared by all instances of the class and do not belong to a single instance.
public class Test {
private static int var1 = 0;
private int var2 = 0;
public static void main(String[] args) {
Test test1 = new Test();
Test test2 = new Test();
var1++;
test1.testMethod();
test2.testMethod();
System.out.println("var1=" + var1);
System.out.println("test1.var2=" + test1.var2);
System.out.println("test2.var2=" + test2.var2);
}
private void testMethod() {
var1++;
var2++;
}
}
will produce the following
var1=3
test1.var2=1
test2.var2=1
Static methods are also shared by all instances of a class so do not have direct access to non-static variables.
In java a class has fields and methods (or functions). Keyword 'static' can be added to both of these entities.
Entities marked with keyword 'static' are class related and other entities are instance related. For accessing static fields or methods of a class we require only the class and its instance (created by using new keyword) is not required to be created.
Methods and fields which are not marked static belong to an active instance of the class.
Now suppose there is a class Test.java and we have no instance of it. We can call any of its method which is marked as static. Try thinking an answer to : "From inside an static method (without an instance of the class) how can we call a method or how can we access a field which belongs to some instance?"
For acessing non static field or method from an static method we need an instance. If the 'calling method' is non static then it must have been invoked on an object. If now we call another method from this non static 'calling method' we can eaisly do that as that method will be invoked on the same object as on which the 'calling method' has been invoked upon.
As mentioned by Xavi in his answer you can also refer to
https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html for understanding about 'static'.
All non static methods and fields have 'this' (https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html) associated with them, which refers to the current active instance of the class.
Hence 'main' method being static can not call any non static method without instance of the class 'Test'
That's lesson 1: create an object from your class:
Test test = new Test ();
test.test(); // will print test
public static void main is a static method, meaning it's not being executed in the context of a particular instance of the class.
Any method not qualified with static needs to be invoked in the context of a specific instance of the class, that's why it's necessary to instance an object or dispose an instance of the class to invoke if from a static context, or to call it from a non-static context such as your public void tst() method.
I'd strongly recommend going through some basic Java tutorials such as Understanding Class Members.
To call static method, you only need the class, while "non-static" we need a instance of the particular class(create an object of the class).

Couple of questions on java method calling

1: I have a program like..
public class Test{
void dispose(){
System.out.println("disposing");
}
Test t=new Test();
public static void main(String[] args){
t.dispose();
}
}
why cant I call dispose method from main()? if its static and non static relation, why the below code works?
public class Test{
void dispose(){
System.out.println("disposing");
}
public static void main(String[] args){
Test t=new Test();
t.dispose();
}
}
2: should always the method call code shold be in method? because, the below code is not working..
public class Test{
void dispose(){
System.out.println("disposing");
}
Test t=new Test();
t.dispose();
public static void main(String[] args){
}
}
Please clarify me..
Example 1
You are in a static method (main) and trying to access a non-static variable t. You have declared the variable t as:
Test t=new Test();
This has created it as a member variable of the class. Instead you need to declare it as:
static Test t=new Test();
Now the static method can access it (although this is generally not a good way to do things).
Example 2
You are now declaring the variable t as a local variable inside the main method so it is valid to access it from within main.
Example 3
With the exception of initalizer blocks (which you don't need to worry about) all code must go inside a method.
I guess you come from a background in Procedural language like C.
Java is different. It's object-orriented.
Coming to your Question . . . .
Ans1: It's correct to say that you don’t necessarily have to create an instance of a class to use the methods of the class. If a method is declared with the static keyword, the method can be called without first creating an instance of the class. That’s because static methods are called from classes, not from objects.
BUT, you can not call non-static method from a static context (here as in static method main()). WHY?
Because you can't call something that doesn't exist. Since you haven't created an object, the non-static method doesn't exist yet. A static method (by definition) always exists.
However even that's not the exact case over here
You may feel that you have created an instance of the class at line 5 of your code but to to the compiler, it doesn't exists. It's outside the main() method, which is the first thing looked for in any run-able Java program. The compiler then ropes in other parts as required. You can't have executable code that is not in a method, look at your object initialization. In second block of code, the compiler sees the object initialization, so program executes.
Ans2: YES. As mentioned before, You can't have executable code that is not in a method
Illustration:
class DeclarationTest
{
int a = 5;
int b = 10;
int c = a + b;//it is Ok, this is a declaration statement for c
/*
int c;
c = a + b; ------> this is not Ok, you are performing an action here this must be inside a method!
*/
}
If that was the case it would make having methods a bit less useful. . . Think about it.
why cant I call dispose method from main()? if its static and non static relation, why the below code works?
Since you have a instance of Test, so you can use that even in static context.
should always the method call code shold be in method?
Yes. exactly. Either in methods, static block or in constructor. Other places not allowed.
Before starting everything let me clear what is an Class variable and an Object Variable
Class Variable : Static variable, which can be accessed without initializing the Class
Object Variable: non static Variable which can only be accessed on CLass instantiation
So in your case, when the main Gets Called, the Class is not initiated, so the object doesnt get initialized, so you cannot call the dispose method.
The reason the second block doesn't work is because of the static relation.
If a method is not static, then it must have an instance to be accessed. That is why, creating an instance of the class allows you to call the method.
If you made the dispose method static, then you could directly call the method since there is only a single instance of it.
Here is a link to a different question that explains it well:
calling non-static method in static method in Java
Hope this helps :)
why cant I call dispose method from main()? if its static and non
static relation, why the below code works?
non-static variable t cannot be referenced from a static context(compiler exception).
You should always remember that the jvm searches for the main() method and executes it. Methods and blocks are initialized after that.
note:- You always compile and run the class which contains the main method.
You are declaring the variable t as a local variable inside the main method so it is valid to access it from within main.
should always the method call code should be in method?
Yes method calls always need to be inside of a method or in the constructor or initialization block, even static block .
When a java program is being executed JVM looks for main method. Within the main if you don't write anything nothing will happen.
public class Test{
void dispose(){
System.out.println("disposing");
}
Test t=new Test(); //That's ok.
t.dispose(); //causes compilation error
public static void main(String[] args){
//Executed as soon as you run your program.
}
}
You want to call dispose(). What do you want? Call dispose() on object of test as t.dispose() or you can call it using Test.dispose();
Method 1:
public class Test{
void dispose(){
System.out.println("disposing");
}
public static void main(String[] args){
Test t=new Test(); //You need a reference to Test object
t.dispose(); //to call its methods
}
}
Is dispose() in Test static? No... So, you must call it by using Test object.
If dispose() in Test static? then...
Method 2:
public class Test{
static void dispose(){
System.out.println("disposing");
}
public static void main(String[] args){
Test.dispose(); // Since dispose() is static.
}
}
You can't call non static methods by using Class Reference. You must use Class object But you can call static methods by using class objects (not recommended). You should call it using Class Reference.
Method 3: (Not recommended)
public class Test{
static void dispose(){
System.out.println("disposing");
}
public static void main(String[] args){
Test t = new Test();
t.dispose(); //Static members should be accessed using class name
}
}
Yes, you can not call non-static object or variables inside static block. If you declare object as static then your code will work as follow.
public class Test{
void dispose(){
System.out.println("disposing");
}
static Test t=new Test();
public static void main(String[] args){
t.dispose();
}
}
You can also try something like below:
public class Test{
void dispose(){
System.out.println("disposing");
}
{
dispose();
}
public static void main(String[] args){
Test t=new Test();
}
}
Also, we can declare object outside method in class but we can not call method outside method or block.

How is the Static method(main) able to grab hold of non static method(constructor) and execute it?

Seems like a very basic query but I was pondering how the static method main() below is able to execute a non static method(the constructor obviously) from it using the new keyword. Though I understand that new brings onto the table a few other things as well but how should I convince myself that this isn't an exception to the rule that static and non static methods can't using non static and static context respectively?
Below is the sample code:
public class ConstructorTest {
ConstructorTest(String str)
{
System.out.println("Constructor Printing "+str);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ConstructorTest cnst=new ConstructorTest("here");
}
}
The above code actually prints --> Constructor Printing here
or in other words executing the body of a Non static method from a Static method?
Any plausible explanations are welcome.
The Java Tutorial states that
[...] Constructors are not members.
Therefore, there is no problem in calling them, since they are not bound to instances of your class. This would not make sense - hence, you cannot do the following:
Thing thing = new Thing();
Thing anotherThing = thing.Thing();
A constructor is not a method, so you cannot apply "method logic" to them.
In case you want to know more, the whole instantiation process is very well documented in the JLS. See 12.5. Creation of New Class Instances.
Actually constructor is compiled into the static method, this is how JVM internally creates instances of classes.
You are executing non-static code, but you are not doing it in a static context.
for instance:
public class C1{
private int x;
public String do(){ System.out.println("x = " + x);}
public static void main(String[] args){
do();
}
}
This can not work, since do is an instance method, which might run code that is specific to the instance. So, how would the VM know which instance to use, or what value x should have?
Now, to first use a constructor, which is possible from any context:
public class C1{
private int x;
public String do(){ System.out.println("x = " + x);}
public static void main(String[] args){
C1 t = new C1();
t.do();
}
}
Here, even though you are calling the method from within a static method, you are using it through an instance, so not in a static context.
ConstructorTest is not a method.
its an constructor,and you can use the constructor for initialize class property.
you can also initialize the static variable from the constructor like that :-
public class XYZ
{
static int i=0;
public XYZ() {
i=1;//not an compile time error
}
public static void doSome(){}
public static void main(String[] args) {
}
}
On a formal language level you should read the line
ConstructorTest cnst = new ConstructorTest("here")
as a class instance creation expression. As a matter of fact, this is not a call to a constructor or any other method.
The instance creation does many steps, like allocating memory for the new object, initializing the fields, calling constructors and initializer blocks. See JLS §12.5 for a detailed step-by-step description. Thus being said, the constructor invocation is only a part of the instance creation.
Additionally, you might see constructors as being static parts of the class. In fact, constructor declaration are not members (see JLS §8.8) and thus they are not overridable (as static methods also). Beware: This is only half true. When being inside the constructor you already have the instance created, and you are able to call other instance methods and/or access instance fields.

Static And Non Static Method Intercall In Java

I am clearing my concepts on Java. My knowledge about Java is on far begineer side, so kindly bear with me.
I am trying to understand static method and non static method intercalls. I know --
Static method can call another static method simply by its name within same class.
Static method can call another non staic method of same class only after creating instance of the class.
Non static method can call another static method of same class simply by way of classname.methodname - No sure if this correct ?
My Question is about non static method call to another non staic method of same class. In class declaration, when we declare all methods, can we call another non static method of same class from a non static class ?
Please explain with example. Thank you.
Your #3, is correct, you can call static methods from non-static methods by using classname.methodname.
And your question seems to be asking if you can call non-static methods in a class from other non-static methods, which is also possible (and also the most commonly seen).
For example:
public class Foo {
public Foo() {
firstMethod();
Foo.staticMethod(); //this is valid
staticMethod(); //this is also valid, you don't need to declare the class name because it's already in this class. If you were calling "staticMethod" from another class, you would have to prefix it with this class name, Foo
}
public void firstMethod() {
System.out.println("This is a non-static method being called from the constructor.");
secondMethod();
}
public void secondMethod() {
System.out.println("This is another non-static method being called from a non-static method");
}
public static void staticMethod() {
System.out.println("This is the static method, staticMethod");
}
}
A method is and should be in the first regard be semantically bound to either the class or the instance.
A List of something has a length or size, so you ask for the size of special List. You need an object of that class to call .size ().
A typical, well known example of a static method is Integer.parseInt ("123");. You don't have an Integer instance in that moment, but want to create one.
If, at all, we would bind that method to an instance, we would bind it to a String instance - that would make sense:
int a = "123".parseInt ();
That would have been a reasonable choice, but it would mean that similar methods for float, double, long, short, Boolean and maybe every class which has a symmetric "toString" method would have to be put into String. That would have meant a zillion of extensions to the String class.
Instead String is final, so a reasonable place to put such a method is the target class, like Integer, Float and so on.
not sure that I understand the question correctly, but non-static methods are the standard way to design classes in OO. Maybe this sample will help spark the discussion:
public class MySampleClass{
private void methodA(){
System.out.println('a called');
}
public void methodB(){
this.methodA();
staticMethod(this);
}
private static void staticMethod( MySampleClass inst ){
inst.methodA();
}
}
You can call non-static method from non-static method using explicitly reference to object on which you want to call that method someObject.method, or without specifying that object someMethod() (in this case it will be invoked on same object that you are invoking current non-static method).
Maybe this will show it better
class Demo {
private String name;
public Demo(String n) {
name = n;
}
public String getName() {// non static method
return name;
}
public void test(Demo d) {// non-static method
System.out.println("this object name is: "+getName());// invoking method on this object
System.out.println("some other object name is: "+d.getName());// invoking method on some other object
}
//test
public static void main(String[] args) {
Demo d=new Demo("A");
Demo d2=new Demo("B");
d.test(d2);
}
}
output:
this object name is: A
some other object name is: B
public class TestClass{
public static void testStatic(){
System.out.println("test1");
}
public void testNonStatic(){
System.out.println("test2");
}
public void test1(){
// both is valid
testStatic();
TestClass.testStatic();
// this is valid, cause it can call the method of the same instance of that class
testNonStatic();
this.testNonStatic();
// this is not valid, cause without a concrete instance of a class you cannot call
// non static methods
TestClass.testNonStatic();
}
public static void test2(){
// again these are both correct
testStatic();
TestClass.testStatic();
// this doesn't work, cause you cannot call non static methods out of static methods
testNonStatic();
this.testNonStatic();
// this instead does work cause you have a concrete instance of the object
TestClass myTestClass = new TestClass();
myTestClass.testNonStatic();
// this still doesn't work
TestClass.testNonStatic();
}
}

Categories