Confusion about static keyword - java

I just read in a document that "A static method can call only other static methods and can not call a non-static method from it". But when I tried to test it I think saw something different.
I have a class C which is described below
import pckage1.*;
public class C
{
public static void main(String par[])
{
}
public static void cc()
{
A ob = new A();
ob.accessA(0);
}
}
where class A is
package pckage1;
public class A
{
public A()
{
}
public void accessA(int x)
{
}
}
Now here from cc STATIC method in class C, a NON STATIC method accessA() is called. How could that be possible if the statement about static method is true?

A static method can call only other static methods and can not call a non-static method from it
That's wrong.
Static methods can call non-static methods as long as they have objects to call the methods on (as you discovered in your code snippet). How else would a non-static method ever be called?
You can't do nonStaticFoo() from a static method, since it is interpreted as this.nonStaticFoo() and since there is no this available in a static method.
Very similar question from earlier today:
Static method access to non-static constructor?

You didn't call a non-static method of your Class.
Try with this :
import pckage1.*;
public class C
{
public static void main(String par[])
{
}
public static void cc()
{
A ob = new A();
ob.accessA(0);
print();
}
public void print()
{
}
}
It won't work, because you're callign a non-static method from a static method, and you don't have an instance of the C class to work with in your static method.

Since every Java program starts executing from a static method, if the statement you cite were true, there would have been no way for any Java program to ever execute an instance method!

A static method has no default context in C, and not this.
However any method can use an intsnace of a class to call a method.

You're calling an instance method, on an instance--you're not trying to call an instance method directly.

You're creating an instance of class A and call a method on it.
So the method you are calling is instance method (not static method).
But you cannot call a non static method of class C.

Related

Call a method when another method is called?

Now I am very aware that you can simply do the following:
public static void methodA() {
doSomeOtherStuffHere();
methodB();
}
public static void methodB() {
doStuffHere();
}
But in my scenario, I cannot change the code of method A ( I cannot add the methodB(); ). So is there any way I can detect when method A is called (and then execute method B when it is)?
You can use Aspect Oriented Programming (https://www.baeldung.com/aspectj) to create aspect which will be executed before YourClass.methodB()
In plain Java, you can do this by creating a subclass of the Class (Which owns methodA) and override the method methodA. Write your own Implementation and use the subclass method where ever you need.
in you code you have "doSomeOtherStuff()" method. You could place methodB within it. Here is an example:
public class App{
public static boolean isCalled = true;
public static void main( String[] args ){
starterMethod();
}
public static void methodB() {
System.out.println("Method B started");
}
public static void starterMethod() {
methodB();
}
}
In you example you can call "doOtherStuffHere". You could call methodB within doOtherStuffHere and that method could contain a call to methodB.

how can i call a method of a class within the main method without using object in java

Hi after a long time i am learning java , i have a confusion in calling the method without the help of the object.
public class VariablesInJava {
int instanceField=5;
static String staticField = "apple";
public void method() {
final String localVariable = "Initial Value";
System.out.println(localVariable);
}
public static void main(String args[]) {
VariablesInJava obj = new VariablesInJava();
System.out.println(obj.instanceField);
System.out.println(obj.staticField);
System.out.println(VariablesInJava.staticField);
System.out.println(new VariablesInJava().instanceField);
obj.method();
}
}
How can i call the method() without the help of object ?
You can create a static method and call the method without creating an object of that class.
Since main method is a static method you either need to create an object of class VariablesInJava and then call it or make the "method" static.
Do this :
public static void method()
Now you can simply call method() without creating an object.
Hope that helps.

Stackoverflow error in overriding static methods of static inner classes

public class StaticInnerClass {
public static void main(String[] args) {
//Outers out=new Outers();
Outers.Inner1 in=new Outers.Inner2();
in.display();
}
}
class Outers
{
static class Inner1
{
static void display()
{
display();
System.out.println("Inner1");
}
}
static class Inner2 extends Inner1
{
static void display()
{
System.out.println("Inner2");
}
}
}
The above program gives a stackoverflow error. Please explain that why doesn't it display "Inner1" because static methods don't override.
The static method that executes is based on the static type, not the instance type:
Outers.Inner1 in=new Outers.Inner2();
So when you call this line, the static type is Outers.Inner1 and therefore it calls the display method that's part of this class, which calls itself repeatedly (causing the StackOverflowError.)
Static methods are not invoked polymorphically!
This will cause the method display to invoke itself again and again until you get Stack Overflow Error. Also, see this question : Polymorphism and Static Methods
A static method can't be overridden by sub class
Static methods should be called with Class not with an object, even though you use object, it still going to use the type of the object.

Do Upcasting effects on Static methods?

Why It calls base class method when we declare method as static in base as well as in derive class and do upcasting.
class Base
{
static void show(){
System.out.println("Base class....");
}
}
class Derive extends Base
{
static void show(){
System.out.println("Drive class....");
}//method hidding.....
public static void main(String[] args)
{
Base b= new Derive();
b.show();
}
}
There are several issues here to mention:
static methods are not inherited and not overridden by the sub-classes
static methods do not need an instance to be called, they need a class
So, basically, calling b.show(); actually means calling Base.show();
You're calling Base.show, not Derive.show. Method hiding is not overriding.
ยง8.4.8.2. of the Java Language Specification gives an example that demonstrates exactly what happens here:
A class (static) method that is hidden can be invoked by using a reference whose type is the class that actually contains the declaration of the method. In this respect, hiding of static methods is different from overriding of instance methods. The example:
class Super {
static String greeting() { return "Goodnight"; }
String name() { return "Richard"; }
}
class Sub extends Super {
static String greeting() { return "Hello"; }
String name() { return "Dick"; }
}
class Test {
public static void main(String[] args) {
Super s = new Sub();
System.out.println(s.greeting() + ", " + s.name());
}
}
produces the output:
Goodnight, Dick
because the invocation of greeting uses the type of s, namely Super, to figure out, at compile time, which class method to invoke, whereas the invocation of name uses the class of s, namely Sub, to figure out, at run-time, which instance method to invoke.
Just one more completion to the answers above. It's best to invoke class methods by their class not by an instance variable: Base.show() not b.show() to make clear that the method is a static method. This is especially useful in your case when you are hiding a method, not overriding it.

Incorporating a non-static return value into a static method?

Is there any technique where you can use the return value of a non-static method from some class in a static method of some other class?
The corrent word for a non-static method is instance method, because it can only be invoked on an instance of its class. So what you need is an instance of the class created with new, then you can invoke instance methods on it.
I suggest reading the introduction to OO concepts in the Java tutorials.
It's hard to know what you're trying to do without any code (even an attempt would be good), but...
Maybe you want the singleton pattern:
public class MyClass {
private static final MyClass INSTANCE = new MyClass();
private MyClass() {}
public static MyClass getInstance() {
return INSTANCE;
}
public int someMethod() {
// return some value;
}
}
then from the other class:
public class TheirClass {
public static int whatever() {
return MyClass.getInstance().someMethod();
}
}
Create an instance of that Class then do a return instance.method();
If you're calling a non-static method, you have to do so against an instance of the class containing that method.
As long as an object of the other type is available within the static method, you can just call the method on that object.
The object can be created within the static method, passed into it as a parameter, or be a static field.
In the static method, create an instance of the class where non-static method is, and call the non-static method on the created object.
There is no other way, because a non-static method can call other non-static static methods, and it can also use the reference to the class instance("this"); so it can only be called on an instance of the class:
public class A{
public int NonStaticMethodA() {
int val;
.....
return val;
}
public int NonStaticMethodB() {
int val=this.NonStaticMethodA();
.....
return val;
}
}
public class B{
public static void StaticMethod() {
A a = new A();
int value = a.NonStaticMethodB();
.....
} }

Categories