I wrote a method just under my main method,
public static LinkList getContents()
then in the main method LinkList list = getContents()
It could only work when I add static in the declaration of getContents, why?
otherwise it will report an error !
A non-static method has to be called on a specific instance of the class e.g. anObject.getContents().
It's a very important concept in Java! Because when calling or referencing things inside of a static method (such as main), you can only reference other static variables, methods, and objects.
Conversely, you can still reference static data from inside non static methods.
The solution for this would be to make an "object" of your class. This starts to get into one of the core concepts of object oriented programming.
Making an object of a class (inside of main) :
ClassName ->pick any name<- = new ClassName();
then you can reference the method like this ->the name you chose.getContents();
Here's some practice code
public class Person{
public void setName(String name){
...
}
public static void main(String[] args){
Person bob = new Person();
bob.setName("pete");
}
}
Related
In the same project I have two packages, 1st package contains a class with this code:
package com.ginger;
public class SimplePrint
{
public SimplePrint(){}
public static void print(Object obj)
{
System.out.println(obj);
}
}
I would like use the method print() in another class in another package, but within the same project.
import com.ginger.*;
public class MainClass
{
public static void main(String[] args)
{
print("Some");
}
}
But the compiler tells me that the method print() is undefined for the 2nd class.
In the same time, I am able to create the object SimplePrint s = new SimplePrint() in the 2nd class.
I'm new to the programming, excuse me if i am asking about the simple thing.
There are a couple of ways to do this:
Non-static
Remove the static keyword of the method print and create an instance of the class
SimplePrint simplePrint = new SimplePrint();
and just do this
simplePrint.print("");
Or combine the above into a single line:
new SimplePrint().print("");
Static
You keep the print method static and just do this
SimplePrint.print("");
static keyword for a method implies its a class level.
If keyword like static is not used for a method it means instance level,so create instance and then access it.
I've read this, and also this and I guess I'm getting the theroical point af static and non static content but I'm unable to apply it to the following case (which is supposed to work) May be so, so, so basic but... humans.
public class MyClass {
private String varA ;
private int varB;
public MyClass(String var, int var) throws SocketException {
//stuff to work with
}
private void methodA() {
//more stuff....
}
public static void main(String args[]) throws IOException {
//How to instatiate MyClass(varA,varC)?
}
}
So, how it's supposed to be instatiated MyClass from main if MyClass is not static?
How to instatiate MyClass(varA,varC) ?
public static void main(String args[]) throws IOException {
//local variables
String varA = "A";
int varC = 10;
//Use the constructor of the class to create an object
MyClass myClassObj = new MyClass(varA, varC);
}
You always need to use the constructors provided by the class to instantiate a class. You don't have the default (no argument) constructor in your class, so you need to pass the constructor arguments as shown above to instantiate the class.
You can look here.
In your MyClass class instance variables varA, varB are created/maintained for each object(instance) separately.
Just to add, if there are any static variables present in a class, they will be maintained only per class (not for each object).
I hope this answer will be helpful for you to understand why main method is static in non-static class
Why is the Java main method static?
Also, in code :
MyClass myClass = new MyClass(varA, varC);
Create new instance of you class using public constructor with your own parameters list.
Agree with JavaGuy.
Just for your clarity's sake, main method is made static so that it can be called from JVM without instantiation of the class. Hence to access any non static member of the class you need to have an instance of the class as mentioned by above solution by JavaGuy.
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();
}
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
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()