Calling Non-Static Method In Static Method In Java [duplicate] - java

This question already has answers here:
Cannot make a static reference to the non-static method
(8 answers)
Closed 5 years ago.
I'm getting an error when I try to call a non-static method in a static class.
Cannot make a static reference to the non-static method methodName() from the type playback
I can't make the method static as this gives me an error too.
This static method cannot hide the instance method from xInterface
Is there any way to get round calling an non-static method in another static method? (The two methods are in seperate packages and seperate classes).

The only way to call a non-static method from a static method is to have an instance of the class containing the non-static method. By definition, a non-static method is one that is called ON an instance of some class, whereas a static method belongs to the class itself.

You could create an instance of the class you want to call the method on, e.g.
new Foo().nonStaticMethod();

Firstly create a class Instance and call the non-static method using that instance.
e.g,
class demo {
public static void main(String args[]) {
demo d = new demo();
d.add(10,20); // to call the non-static method
}
public void add(int x ,int y) {
int a = x;
int b = y;
int c = a + b;
System.out.println("addition" + c);
}
}

public class StaticMethod{
public static void main(String []args)throws Exception{
methodOne();
}
public int methodOne(){
System.out.println("we are in first methodOne");
return 1;
}
}
the above code not executed because static method must have that class reference.
public class StaticMethod{
public static void main(String []args)throws Exception{
StaticMethod sm=new StaticMethod();
sm.methodOne();
}
public int methodOne(){
System.out.println("we are in first methodOne");
return 1;
}
}
This will be definitely get executed. Because here we are creating reference which nothing but "sm" by using that reference of that class which is nothing
but (StaticMethod=new Static method()) we are calling method one (sm.methodOne()).
I hope this will be helpful.

You need an instance of the class containing the non static method.
Is like when you try to invoke the non-static method startsWith of class String without an instance:
String.startsWith("Hello");
What you need is to have an instance and then invoke the non-static method:
String greeting = new String("Hello World");
greeting.startsWith("Hello"); // returns true
So you need to create and instance to invoke it.

It sounds like the method really should be static (i.e. it doesn't access any data members and it doesn't need an instance to be invoked on). Since you used the term "static class", I understand that the whole class is probably dedicated to utility-like methods that could be static.
However, Java doesn't allow the implementation of an interface-defined method to be static. So when you (naturally) try to make the method static, you get the "cannot-hide-the-instance-method" error. (The Java Language Specification mentions this in section 9.4: "Note that a method declared in an interface must not be declared static, or a compile-time error occurs, because static methods cannot be abstract.")
So as long as the method is present in xInterface, and your class implements xInterface, you won't be able to make the method static.
If you can't change the interface (or don't want to), there are several things you can do:
Make the class a singleton: make the constructor private, and have a static data member in the class to hold the only existing instance. This way you'll be invoking the method on an instance, but at least you won't be creating new instances each time you need to call the method.
Implement 2 methods in your class: an instance method (as defined in xInterface), and a static method. The instance method will consist of a single line that delegates to the static method.

The only way to call a non-static method from a static method is to have an instance of the class containing the non-static method.
class A
{
void method()
{
}
}
class Demo
{
static void method2()
{
A a=new A();
a.method();
}
/*
void method3()
{
A a=new A();
a.method();
}
*/
public static void main(String args[])
{
A a=new A();
/*an instance of the class is created to access non-static method from a static method */
a.method();
method2();
/*method3();it will show error non-static method can not be accessed from a static method*/
}
}

There are two ways:
Call the non-static method from an instance within the static method. See fabien's answer for an oneliner sample... although I would strongly recommend against it. With his example he creates an instance of the class and only uses it for one method, only to have it dispose of it later. I don't recommend it because it treats an instance like a static function.
Change the static method to a non-static.

You can't get around this restriction directly, no. But there may be some reasonable things you can do in your particular case.
For example, you could just "new up" an instance of your class in the static method, then call the non-static method.
But you might get even better suggestions if you post your class(es) -- or a slimmed-down version of them.

The easiest way to use a non-static method/field within a a static method or vice versa is...
(To work this there must be at least one instance of this class)
This type of situation is very common in android app development eg:- An Activity has at-least one instance.
public class ParentClass{
private static ParentClass mParentInstance = null;
ParentClass(){
mParentInstance = ParentClass.this;
}
void instanceMethod1(){
}
static void staticMethod1(){
mParentInstance.instanceMethod1();
}
public static class InnerClass{
void innerClassMethod1(){
mParentInstance.staticMethod1();
mParentInstance.instanceMethod1();
}
}
}
Note:- This cannot be used as a builder method like this one.....
String.valueOf(100);

I use an interface and create an anonymous instance of it like so:
AppEntryPoint.java
public interface AppEntryPoint
{
public void entryMethod();
}
Main.java
public class Main
{
public static AppEntryPoint entryPoint;
public static void main(String[] args)
{
entryPoint = new AppEntryPoint()
{
//You now have an environment to run your app from
#Override
public void entryMethod()
{
//Do something...
System.out.println("Hello World!");
}
}
entryPoint.entryMethod();
}
public static AppEntryPoint getApplicationEntryPoint()
{
return entryPoint;
}
}
Not as elegant as creating an instance of that class and calling its own method, but accomplishes the same thing, essentially. Just another way to do it.

It is not possible to call non-static method within static method. The logic behind it is we do not create an object to instantiate static method, but we must create an object to instantiate non-static method. So non-static method will not get object for its instantiation inside static method, thus making it incapable for being instantiated.

Constructor is a special method which in theory is the "only" non-static method called by any static method. else its not allowed.

You can call a non static method within a static one using:
Classname.class.method()

Related

#Override on static methods? [duplicate]

I'd like to know:
Why can't static methods be overridden in Java?
Can static methods be overloaded in Java?
Static methods can not be overridden in the exact sense of the word, but they can hide parent static methods
In practice it means that the compiler will decide which method to execute at the compile time, and not at the runtime, as it does with overridden instance methods.
For a neat example have a look here.
And this is java documentation explaining the difference between overriding instance methods and hiding class (static) methods.
Overriding: Overriding in Java simply means that the particular method would be called based on the run time type of the object and
not on the compile time type of it (which is the case with overriden
static methods)
Hiding: Parent class methods that are static are not part of a child class (although they are accessible), so there is no question of
overriding it. Even if you add another static method in a subclass,
identical to the one in its parent class, this subclass static method
is unique and distinct from the static method in its parent class.
Static methods can not be overridden because there is nothing to override, as they would be two different methods. For example
static class Class1 {
public static int Method1(){
return 0;
}
}
static class Class2 extends Class1 {
public static int Method1(){
return 1;
}
}
public static class Main {
public static void main(String[] args){
//Must explicitly chose Method1 from Class1 or Class2
Class1.Method1();
Class2.Method1();
}
}
And yes static methods can be overloaded just like any other method.
Static methods cannot be overridden because they are not dispatched on the object instance at runtime. The compiler decides which method gets called.
This is why you get a compiler warning when you write
MyClass myObject = new MyClass();
myObject.myStaticMethod();
// should be written as
MyClass.myStaticMethod()
// because it is not dispatched on myObject
myObject = new MySubClass();
myObject.myStaticMethod();
// still calls the static method in MyClass, NOT in MySubClass
Static methods can be overloaded (meaning that you can have the same method name for several methods as long as they have different parameter types).
Integer.parseInt("10");
Integer.parseInt("AA", 16);
Parent class methods that are static are not part of a child class (although they are accessible), so there is no question of overriding it. Even if you add another static method in a subclass, identical to the one in its parent class, this subclass static method is unique and distinct from the static method in its parent class.
Static methods can not be overridden because they are not part of the object's state. Rather, they belongs to the class (i.e they are class methods). It is ok to overload static (and final) methods.
Overloading is also called static binding, so as soon as the word static is used it means a static method cannot show run-time polymorphism.
We cannot override a static method but presence of different implementations of the same static method in a super class and its sub class is valid. Its just that the derived class will hide the implementations of the base class.
For static methods, the method call depends on the type of reference and not which object is being referred, i.e. Static method belongs only to a class and not its instances , so the method call is decided at the compile time itself.
Whereas in case of method overloading static methods can be overloaded iff they have diff number or types of parameters. If two methods have the same name and the same parameter list then they cannot be defined different only by using the 'static' keyword.
If I m calling the method by using SubClass name MysubClass then subclass method display what it means static method can be overridden or not
class MyClass {
static void myStaticMethod() {
System.out.println("Im in sta1");
}
}
class MySubClass extends MyClass {
static void myStaticMethod() {
System.out.println("Im in sta123");
}
}
public class My {
public static void main(String arg[]) {
MyClass myObject = new MyClass();
myObject.myStaticMethod();
// should be written as
MyClass.myStaticMethod();
// calling from subclass name
MySubClass.myStaticMethod();
myObject = new MySubClass();
myObject.myStaticMethod();
// still calls the static method in MyClass, NOT in MySubClass
}
}
No,Static methods can't be overriden as it is part of a class rather than an object.
But one can overload static method.
Static methods are a method whose single copy is shared by all the objects of the class. A static method belongs to the class rather than objects. since static methods are not dependent on the objects, Java Compiler need not wait till the creation of the objects so to call a static method we use syntax like ClassName.method() ;
In the case of method overloading, methods should be in the same class to overload.even if they are declared as static it is possible to overload them as,
Class Sample
{
static int calculate(int a,int b,int c)
{
int res = a+b+c;
return res;
}
static int calculate(int a,int b)
{
int res = a*b;
return res;
}
}
class Test
{
public static void main(String []args)
{
int res = Sample.calculate(10,20,30);
}
}
But in the case of method overriding, the method in the super class and the method in the sub class act as a different method. the super class will have its own copy and the sub class will have its own copy so it does not come under method overriding.
class SuperType {
public static void classMethod(){
System.out.println("Super type class method");
}
public void instancemethod(){
System.out.println("Super Type instance method");
}
}
public class SubType extends SuperType{
public static void classMethod(){
System.out.println("Sub type class method");
}
public void instancemethod(){
System.out.println("Sub Type instance method");
}
public static void main(String args[]){
SubType s=new SubType();
SuperType su=s;
SuperType.classMethod();// Prints.....Super type class method
su.classMethod(); //Prints.....Super type class method
SubType.classMethod(); //Prints.....Sub type class method
}
}
This example for static method overriding
Note: if we call a static method with object reference, then reference type(class) static method will be called, not object class static method.
Static method belongs to class only.
static methods are class level methods.
Hiding concept is used for static methods.
See : http://www.coderanch.com/how-to/java/OverridingVsHiding
The very purpose of using the static method is to access the method of a class without creating an instance for it.It will make no sense if we override that method since they will be accessed by classname.method()
No, you cannot override a static method. The static resolves against the class, not the instance.
public class Parent {
public static String getCName() {
return "I am the parent";
}
}
public class Child extends Parent {
public static String getCName() {
return "I am the child";
}
}
Each class has a static method getCName(). When you call on the Class name it behaves as you would expect and each returns the expected value.
#Test
public void testGetCNameOnClass() {
assertThat(Parent.getCName(), is("I am the parent"));
assertThat(Child.getCName(), is("I am the child"));
}
No surprises in this unit test. But this is not overriding.This declaring something that has a name collision.
If we try to reach the static from an instance of the class (not a good practice), then it really shows:
private Parent cp = new Child();
`enter code here`
assertThat(cp.getCName(), is("I am the parent"));
Even though cp is a Child, the static is resolved through the declared type, Parent, instead of the actual type of the object. For non-statics, this is resolved correctly because a non-static method can override a method of its parent.
You can overload a static method but you can't override a static method. Actually you can rewrite a static method in subclasses but this is not called a override because override should be related to polymorphism and dynamic binding. The static method belongs to the class so has nothing to do with those concepts. The rewrite of static method is more like a shadowing.
I design a code of static method overriding.I think It is override easily.Please clear me how its unable to override static members.Here is my code-
class Class1 {
public static int Method1(){
System.out.println("true");
return 0;
}
}
class Class2 extends Class1 {
public static int Method1(){
System.out.println("false");
return 1;
}
}
public class Mai {
public static void main(String[] args){
Class2 c=new Class2();
//Must explicitly chose Method1 from Class1 or Class2
//Class1.Method1();
c.Method1();
}
}
It’s actually pretty simple to understand – Everything that is marked static belongs to the class only, for example static method cannot be inherited in the sub class because they belong to the class in which they have been declared. Refer static keyword.
The best answer i found of this question is:
http://www.geeksforgeeks.org/can-we-overload-or-override-static-methods-in-java/
As any static method is part of class not instance so it is not possible to override static method
From Why doesn't Java allow overriding of static methods?
Overriding depends on having an instance of a class. The point of polymorphism is that you can subclass a class and the objects implementing those subclasses will have different behaviors for the same methods defined in the superclass (and overridden in the subclasses). A static method is not associated with any instance of a class so the concept is not applicable.
There were two considerations driving Java's design that impacted this. One was a concern with performance: there had been a lot of criticism of Smalltalk about it being too slow (garbage collection and polymorphic calls being part of that) and Java's creators were determined to avoid that. Another was the decision that the target audience for Java was C++ developers. Making static methods work the way they do have the benefit of familiarity for C++ programmers and were also very fast because there's no need to wait until runtime to figure out which method to call.
Definitely, we cannot override static methods in Java.
Because JVM resolves correct overridden method based upon the object at run-time by using dynamic binding in Java.
However, the static method in Java is associated with Class rather than the object and resolved and bonded during compile time.

Returning a class object from static method [duplicate]

This question already has answers here:
Why can't we use 'this' keyword in a static method
(9 answers)
Closed 4 years ago.
I'm exercising static keyword. I've declared a static method whose return type is class. when I access this method from main method is gives me following error. How can I return the object from this method?
error: non-static variable this cannot be referenced from a static context
return this;
Following is my code
public class StaticKeyword{
public static StaticKeyword run(){
return this;
}
public static void main(String args[]){
System.out.println(StaticKeyword.run());
}
}
A static method or a static variable belongs to a class and not the instance of the class. this is an instance variable which points to the current reference.
Hence this cannot be used within a static block. So, you should rephrase your code something like this,
public static class StaticKeyword {
public static StaticKeyword run(){
return new StaticKeyword();
}
public static void main(String args[]){
System.out.println(StaticKeyword.run());
}
}
Also keep in mind that a method which is declared as static would remain in main memory forever (ie' until the java process stops). Unless and until you would use this method very frequently something like a util classes and methods could be made as static
For each access without creating an object
For faster access - since it is static the method would be already there in main memory during the consecutive method calls.
When you do not use the method frequently it is always good to go with accessing the method by creating an instance to the corresponding class.
You need to change it to this:
public static class StaticKeyword {
public static StaticKeyword run(){
StaticKeyword returnObject = new StaticKeyword();
return returnObject;
}
public static void main(String args[]){
System.out.println(StaticKeyword.run());
}
}
this is a reference to the current object — the object whose method or constructor is being called. However no instance is created to be returned. So you will need to do something like return new StaticKeyword()
also tip: I personally struggled when I was learning the keyword static. It is a good rule of thumb to ask yourself "Do I want to call this method even if there is no instance of this Obj exist?" If so then your method should be static.

Static method in java can call non static method

It is said in java that we can not call a non-static method from a static method..what does this mean exactly ?we can always call a non static method frm static one using object although..'pls explan
Here is a nice code piece to illustrate what it means:
class MyClass{
static void func1(){
func2(); //This will be an error
}
void func2(){
System.out.println("Hello World!");
}
}
To call a non-static method, you need an instance (object) - because these methods belong to an instance, and in general only make sense in the context of an instance.
Static methods don't belong to an instance - they belong to the class. So there is no need to create an instance first, you can just call MyClass.doSomething()
void foo(){
MyClass.doSomething();
}
But you can call a non-static method from a static method provided you first create an instance.
static void bar(){
MyObject o = new MyObject();
o.doSomething();
}

why can't I create another method aside from main method in main class?

I'm beginner in Java and I have a basic question about main class and main method.I try to create method such as addition under the main method . throw the error like "non-static method". what is reason ? thanks...
I guess you using a code like this.
public class TestClass {
public static void main(String[] args) {
doSth();
}
public void doSth() {
}
You cannot call a non-static method from the main class.
If you want to call a non-static method from your main class, instance your class like this:
TestClass test = new TestClass();
test.doSth();
and call the method.
A static method means that you don't need to invoke the method on an instance(Object). A non-static (instance) method requires that you invoke it on an instance. So think about it: if I have a method changeThisItemToTheColorBlue() and I try to run it from the main method, what instance would it change? It doesn't know. You can run an instance method on an instance, like someItem.changeThisItemToTheColorBlue().
More information at http://en.wikipedia.org/wiki/Method_(computer_programming)#Static_methods
The only way to call a non-static method from a static method is to have an instance of the class containing the non-static method. By definition, a non-static method is one that is called ON an instance of some class, whereas a static method belongs to the class itself.
Is like when you try to invoke the non-static method startsWith of class String without an instance:
String.startsWith("Hello");
What you need is to have an instance and then invoke the non-static method:
String greeting = new String("Hello World");
greeting.startsWith("Hello"); // returns true
So you need to create and instance to invoke it.
And to be more clear about Static methods you can refer
https://softwareengineering.stackexchange.com/questions/211137/why-can-static-methods-only-use-static-data
You defined your method without the keyword 'static' I think.
You cannot call a non-static method in a static context such as the main method.
See Java Object Oriented Programming
The main method is a static method, so it does not exist inside an object.
To call non-static methods (methods without the "static" keyword in front of their definitions), you need to create an object of the class, using new.
You can just make the other method static, that will fix the immediate problem. But it may or may not be good Object Oriented design to do this. It would depend on what you were trying to do.
You can't call a non-static method from a static method without instantiation of the class. If you'd like to call another method without creating a new instance (a new object) of the main class you have to use the static keyword for the another method also.
package maintestjava;
public class Test {
// static main method - this is the entry point
public static void main(String[] args)
{
System.out.println(Test.addition(10, 10));
}
// static method - can be called without instantiation
public static int addition(int i, int j)
{
return i + j;
}
}
If you would like to call non static methods you have to instatiate the class, this way creating a new instance, an object of the class:
package maintestjava;
public class Test {
// static main method - this is the entry point
public static void main(String[] args)
{
Test instance = new Test();
System.out.println(instance.addition(10, 10));
}
// public method - can be called with instantiation on a created object
public int addition(int i, int j)
{
return i + j;
}
}
See more:
Static keyword on wikipedia
Static on about.com

Java Static [duplicate]

This question already has answers here:
Closed 14 years ago.
Duplicate: What does the 'static' keyword do in a class?
I've read this post already.
What does the "static" keyword in a method do?
I remember being told that static != clingy...but that is pretty much all I know about this keyword.
Static class variables can be thought of as a global class. No matter how many instances of the class you have, there is just one instance of each static variable.
Static methods don't use any non-static class variables and they can be called directly from outside of the class without having to instantiate the class itself.
Static variables and methods belong to the class and not instance, although you can refer them from an instance reference. Usually, you use the Class name to access them.
If a method is declared as static, you don't need the object's instance in which it is defined to invoke it. Now, you might want to know when could such a situation arise? Consider the main method of java
public static void main(String[] args)
Why is it declared static? It's because in order to start your program this method should begin execution. And, since the program hasn't initialized there is no way you could create an instance of the class in which it is declared. Therefore, you are required to declare the class as public. And, this static method gets called when the class is loaded in memory through
java YourClassName
Besides this, static methods are used to modify static variables. They cannot manipulate non-static instance variables.
Also, be aware, that static holds a different meaning in another language like C.
A static method belongs to the Class it is defined in and not to instances of objects of that Class, as non-static methods do. As a side-effect of not belonging to the instances of a Class, it's a compile error to try and access non-static fields in a static method. There's no "this" for the static methods to get access of the non-static fields from.
The Java Math class is a great example because it's loaded with static methods. You never create an instance of the Math class, you just call methods directly from the class.
Math.abs(3.14);
The value of a static variable within a method is stored between calls to that method
public void method() {
static int callCount = 0;
callCount++;
System.out.println("Calls: " + callCount);
}
method(); // "Calls: 1"
method(); // "Calls: 2"
method(); // "Calls: 3"
Note that this is completely different from a static method. A static method is called upon the class it is defined in instead of an instance of this class.
class MyClass {
public static void staticMethod() { ... }
public void nonStaticMethod();
}
Myclass.staticMethod();
MyClass instance = new MyClass();
instance.nonStaticMethod();
a static method is one that's established for the class. It doesn't need (and doesn't have) a this pointer, and can't access instance data. So you can write something ike
public class Hello {
void instanceHello() {
System,out.println("Hello from the instance.");
}
public static void main(int argc, String[] argv){
// The main method is defined even though there are no instances
System.out.println("Hello from main.");
instanceHello(); // but this is a syntax error;
Hello h = new Hello();
h.instanceHello(); // this isn't though
}
}

Categories

Resources