I'm still learning about methods in Java and was wondering how exactly you might use an instance method. I was thinking about something like this:
public void example(String random) {
}
However, I'm not sure if this is actually an instance method or some other type of method. Could someone help me out?
If it's not a static method then it's an instance method. It's either one or the other. So yes, your method,
public void example(String random) {
// this doesn't appear to do anything
}
is an example of an instance method.
Regarding
and was wondering how exactly you might use an instance method
You would create an instance of the class, an object, and then call the instance method on the instance. i.e.,
public class Foo {
public void bar() {
System.out.println("I'm an instance method");
}
}
which could be used like:
Foo foo = new Foo(); // create an instance
foo.bar(); // call method on it
class InstanceMethod
{
public static void main(String [] args){
InstanceMethod obj = new InstanceMethod();// because that method we wrote is instance we will write an object to call it
System.out.println(obj.sum(3,2));
}
int f;
public double sum(int x,int y){// this method is instance method because we dont write static
f = x+y;
return f;
}
}
*An instance method * is a method is associated with objects, each instance method is called with a hidden argument that refers to the current object.
for example on an instance method :
public void myMethod {
// to do when call code
}
Instance method means the object of your class must be created to access the method. On the other hand, for static methods, as its a property of Class and not that of its object/instance, it is accessed without creating any instance of the class. But remember static methods can only access static variables, where as instance method can access the instance variables of your class.
Static methods and static variables are useful for memory management as it does not require to declare objects which would otherwise occupy memory.
Example of instance method and variable :
public class Example {
int a = 10; // instance variable
private static int b = 10; // static variable (belongs to the class)
public void instanceMethod(){
a =a + 10;
}
public static void staticMethod(){
b = b + 10;
}
}
void main(){
Example exmp = new Example();
exmp.instanceMethod(); // right
exmp.staticMethod(); // wrong..error..
// from here static variable and method cant be accessed.
}
Instance methods are the methods that require an object to access them where as static methods do not. The method that you mentioned is an instance method since it does not contain static keyword.
Example of instance method:
class main
{
public void instanceMethod()//instance method
{
System.out.println("Hello world");
}
}
The above method can be accessed with an object:
main obj=new main();//instance of class "main"
obj.instanceMethod();//accessing instance method using object
Hope this might help you.
Instance block with Cases { Static , constructor , Local method )
OutPut will be :
Related
A static method belongs to the class rather than object of a class.
A static method can be invoked without the need for creating an instance of a class. What does it mean?
It means that, rather than needing to create a new instance from the class and then calling the function like:
Foo f = new Foo();
f.bar();
you can instead access it directly from the class like:
Foo.bar();
That obviously means that you can't use any non-static field or method of the object from a static method, of course.
ClassObject classObj = new ClassObject();
classObj.doSomething();
vs.
ExampleClass.staticMethod();
First one needs an instance of ClassObject to call doSomething(). The second one doesn't.
Here is an example of a class with a static method and standard method.
public class MyClass {
public static void staticPrintMe() {
System.out.println("I can be printed without any instantiation of MyClass class");
}
public void nonStaticPrintMe() {
System.out.println("I can be printed only from an object of type MyClass");
}
}
And here is the code to call both methods:
MyClass.staticPrintMe(); // Called without instantiating MyClass
MyClass myClassInstance = new MyClass(); // MyClass instantiation
myClass.nonStaticPrintMe(); // Called on object of type MyClass
As you can see the static method is invoked without any object of type MyClass.
Take the java.lang.Math class as an example. In this line of code:
double pi = 2 * Math.asin(1);
I've referred to the Math class, but the asin method is static. There's no instance of the class created, the class just acts as a placeholder for this utility function.
A corollary of this is that a static method may not access any per-instance data - it can only access class variables that are also declared static.
Look at this example. Defining a class with both an static method and an instance method:
public class MyClass {
public MyClass() {
// do something
}
public static staticMethod() {
// do something
}
public void instanceMethod() {
// do something
}
}
Usage:
MyClass anInstance = new MyClass();
// static method:
MyClass.staticMethod();
// instance method:
anInstance.instanceMethod();
// this is possible thought discoraged:
anInstance.staticMethod();
// this is forbidden:
MyClass.instanceMethod();
To invoke static method you do not need to build a class instance (i.e object).
For example:
class Multiplier {
public static double multiply(double arg1, double arg2) {
return arg1 * arg2;
}
}
static method does not use class instance information, and you can use the method as:
Multiplier.multiply(x, y);
non-static method uses class instance information and depends on it.
for example:
class Pony {
private Color color;
private String name;
public Pony(Color color, String Name) {
this.color = color;
this.name = name;
}
public void printPonyInfo() {
System.out.println("Name: " + this.name);
System.out.println("Color: " + this.color);
}
}
Pony pony1 = new Pony(Color.PINK, "Sugar");
Pony pony2 = new Pony(Color.BLACK, "Jupiter");
and when you call:
pony1.printPonyInfo();
pony2.printPonyInfo();
You get name and color for every pony object. You cannot call Pony.printPonyInfo() because printPonyInfo() does not know, what to print. It is not static. Only when you have created Pony class instance, you can call this method, that depends on the class instance information.
When we call a method, we need an instace of a class like this.
class SomeClass {
public void test() {}
}
SomeClass obj = new SomeClass();
obj.test();
'obj' is an instance of SomeClass.
Without an instance like 'obj', we can't call the test method.
But the static method is different.
class SomeClass2 {
public static void testStatic() {}
}
We don't call the testStatic method like above case of SomeClass.
SomeClass2 obj = new SomeClass2();
obj.testStatic(); // wrong
We just call with only class type.
SomeClass2.testStatic();
I have a class which has static members also non-static members like :
public class StaticClassObjectCreations {
public static void doSomeThing() {
// TODO implementations static
}
public void nonStaticMethod() {
// TODO implementations for non static
}
public static void main(String[] args) {
StaticClassObjectCreations obj = new StaticClassObjectCreations();
StaticClassObjectCreations obj1 = new StaticClassObjectCreations();
}
}
as we can see the number of object creation is not restricted and the non-static methods can be accessed with the help of objects created with new keyword.
the static methods or member variables will be also available for each instance and they can be accessed with out creating objects also.
now my question is : How the JVM maintains the instances for static block of code or in other words what happens to these static blocks when creating objects with new keyword.
thanks.
Static blocks/variable/methods are belong to Class, not instances of that Class. They will be initialized when the Class was loaded. There won't be any effect to these when you create instance of the Class. Even if you invoke a static member from an instance, compiler will replace instance with its Class.
Say you have classes A,B and C.
You have initialised a static array called "dataArray" in A.
You created an instance (object) of A in B and one in C.
The initialisation of these two objects will not affect "dataArray" in A since it is static. It will hold the same data for object in B and C. This is because static variables and methods are at class level, not object level.
Note: This is based on my experiments. If I am wrong, please respond.
If your question is about how the compiler treats a static method call using object reference,
public class StaticClassObjectCreations {
public static void doSomeThing() {
System.out.println("here");
}
public static void main(String[] args) {
StaticClassObjectCreations obj = null;
obj.doSomeThing();
StaticClassObjectCreations.doSomeThing();
}
}
compiler replaces object reference with its corresponding class to invoke the static method. Even if obj is null compiler wont give a null pointer because it doesnt need an object reference to invoke a static method.
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
class XYZ{
public static void show(){
System.out.println("inside XYZ");
}
}
public class StaticTest extends XYZ {
public static void show() {
System.out.println("inside statictest");
}
public static void main(String args[]){
StaticTest st =new StaticTest();
StaticTest.show();
}
}
though we know static methods cant be overridden. Then what actually is happening?
Static methods belong to the class. They can't be overridden. However, if a method of the same signature as a parent class static method is defined in a child class, it hides the parent class method. StaticTest.show() is hiding the XYZ.show() method and so StaticTest.show() is the method that gets executed in the main method in the code.
Its not overriding they are two different method in two different class with same signature. but method from XYZ isn't available in child class through inheritance .
It will call method from StaticTest
It's not overriden properly said... Static methods are 'tied' to the class so
StaticTest.show();
and
XYZ.show();
are two totally different things. Note you can't invoke super.show()
To see the difference you have to use more powerful example:
class Super {
public static void hidden(Super superObject) {
System.out.println("Super-hidden");
superObject.overriden();
}
public void overriden() {
System.out.println("Super-overriden");
}
}
class Sub extends Super {
public static void hidden(Super superObject) {
System.out.println("Sub-hidden");
superObject.overriden();
}
public void overriden() {
System.out.println("Sub-overriden");
}
}
public class Test {
public static void main(String[] args) {
Super superObject = new Sub();
superObject.hidden(superObject);
}
}
As Samit G. already have written static methods with same signature in both base and derived classes hide the implementation and this is no-overriding. You can play a bit with the example by changing the one or the another of the static methods to non-static or changing them both to non-static to see what are the compile-errors which the java compiler rises.
It's not an override, but a separate method that hides the method in XYZ.
So as I know, any static member (method or state) is an attribute of a class, and would not be associated with any instance of a class. So in your example, XYZ is a class, and so is StaticTest (as you know). So by calling the constructor two things first happen. An Object of type Class is created. It has a member on it call showed(). Class, XYZ.class, extends from Object so has all those Object methods on it plus show(). Same with the StaticClass, the class object has show() on it as well. They both extend java.lang.Object though. An instance of StaticClass would also be an instance of XYZ. However now the more interesting question would be what happens when you call show() on st?
StaticClass st = new StaticClass();
st.show();
XYZ xyz = st;
xyz.show();
What happens there? My guess is that it is StaticClass.show() the first time and XYZ.show() the second.
Static methods are tied to classes and not instances (objects).
Hence the invocations are always ClassName.staticMethod();
When such a case of same static method in a subclass appears, its called as refining (redefining) the static method and not overriding.
// Java allows a static method to be called from an Instance/Object reference
// which is not the case in other pure OOP languages like C# Dot net.
// which causes this confusion.
// Technically, A static method is always tied to a Class and not instance.
// In other words, the binding is at compile-time for static functions. - Early Binding
//
// eg.
class BaseClass
{
public static void f1()
{
System.out.println("BaseClass::f1()...");
} // End of f1().
}
public class SubClass extends BaseClass
{
public static void f1()
{
System.out.println("SubClass::f1()...");
// super.f1(); // non-static variable super cannot be referenced from a static context
} // End of f1().
public static void main(String[] args)
{
f1();
SubClass obj1 = new SubClass();
obj1.f1();
BaseClass b1 = obj1;
b1.f1();
} // End of main().
} // End of class.
// Output:
// SubClass::f1()...
// SubClass::f1()...
// BaseClass::f1()...
//
//
// So even though in this case, called with an instance b1 which is actually referring to
// an object of type SuperClass, it calls the BaseClass:f1 method.
//
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()