How static method call without mentioning the class name [duplicate] - java

This question already has answers here:
Static method invocation
(5 answers)
Closed 4 years ago.
How static method invoke without mentioning the class name?.ex-below
class Test {
public static void staticMethodOne() {
System.out.println("Static method one");
}
public void instanceMethodOne() {
staticMethodOne();//Call static method without mentioning the class
//name
Test.staticMethodOne();//call from class name
new Test().staticMethodOne();//calling from object ref
}
public static void staticMethodTwo() {
staticMethodOne();
}
}

Since you are accessing it in the same class, you doesn't need an instance just like any other instance method.

Any local method can be invoked without being qualified by class name (for static methods) or this keyword (for instance method) from within the same class, assuming that you don't call instance methods from static contexts.
Additionally, you can call static methods (almost) without qualifying them if you add a static import:
import static java.lang.String.format;
And in method
String formatted = format("this is format from %s", "String");

Related

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.

Use of non static method in Java [duplicate]

This question already has answers here:
Difference between Static methods and Instance methods
(10 answers)
Closed 4 years ago.
I want to know, what is the use of the non-static method. My understanding is that static methods can be called directly as well as by the object of the class while nonstatic methods can only be called by an object of the class.
class Ideone
{
public static void print()
{
System.out.println("print");
}
public static void main (String[] args) throws java.lang.Exception
{
Ideone id = new Ideone();
id.print();
print();
}
}
The above method can be called directly as well as by an object of class. So, when should I have a non static method?
In real-world applications objects interacts with other objects and generally have one starting point say main method in some java application.
You CAN NOT invoke other objects nonstatic methods without creating them.

Java static methods vs overriding [duplicate]

This question already has answers here:
Why doesn't Java allow overriding of static methods?
(22 answers)
If static methods can't be overridden, how its working here (For Java)?
(3 answers)
Why doesn't the compiler complain when I try to override a static method?
(9 answers)
Closed 4 years ago.
Trying to work on an example from a book on method overriding.
The code has two classes Veggies and Pumpkin.The only confusion i have is if the object of pumpkin is assigned to the myveggie object, why does it call the method of veggies class since the object is from derived class.
I am sure this has something to do with static method,but I could get a more clear idea.
class Veggies {
public static void staticMethod(){
System.out.println("Veggies static method");
}
public void instancemethod(){
System.out.println("Veggies instance method");
}
}
public class Pumpkin extends Veggies{
public static void staticMethod(){
System.out.println("Pumpkin static method");
}
#Override
public void instancemethod(){
System.out.println("Pumpkin instance method");
}
public static void main(String[] args) {
Pumpkin myPumpkin=new Pumpkin();
Veggies myveggie=myPumpkin;
myveggie.staticMethod();
myveggie.instancemethod();
}
}
As this question:
Why doesn't Java allow overriding of static methods?
explains, static methods cannot be overridden in Java.
What you have in your example, is code that is calling a static method via an instance. This is bad practice.
What actually happens is that the static type of the variable (not the reference!) is resolved at compile time to a class. In this case, the class is Veggies. Then the compiler inserts a call to the static method of that class; i.e. Veggies.staticMethod().
Which is confusing ... because it looks like you should be dispatching to a static method associated with the reference. But that is not how Java works.
That's why this is bad practice, and why a lot of IDEs will warn you about it.

Static method overriding in Java [duplicate]

This question already has answers here:
Why doesn't Java allow overriding of static methods?
(22 answers)
Is it possible to override a static method in derived class?
(6 answers)
Closed 5 years ago.
class B extends A {
static public void printMe(){
System.out.println("in static B");
}
}
class A{
static public void printMe(){
System.out.println("In static A");
}
}
public static void main(String[] args) {
A a = new B();
a.printMe();
}
Why is the output "In static A" ?
Static members bind to type rather than implemented type. Hence you see the methods executing from class A.
And static members are not to be ovverriden and they share same copy regardless of instance state.
If you need methods to be ovveriden, do not use them as static members.
Static member or method belongs to class level instead of specific instance.
A static class will have only 1 instance even if you create multiple instance or do not create instance.
In your case, since you have created instance of class A, method inside class A is implemented.
Another way to get a clear concise for the problem scenario is try running the code mentioned below:
public static void main(String[] args) {
A.printMe();
}
You will get clear idea.

why is it allowed to call a static method with a reference to an instance of the class? [duplicate]

This question already has answers here:
Is it possible to override a static method in derived class?
(6 answers)
Closed 7 years ago.
lets assume that i have 2 classes.
ParentClass:
public class ParentClass {
public static void getInstance(){
System.out.println("Parent method");
}
}
ChildClass:
public class ChildClass extends ParentClass {
public static void getInstance(){
System.out.println("child method");
}
public static void main(String args[]){
ParentClass pc=new ChildClass();
pc.getInstance();
}
}
as you notice above both classes has a static method called getInstance() and in java and many other languages if there is an inherited method and you have the same method in the child class the method that get executed is one in the child class.
the question is: why pc.getInstance(); calls the method in the parent class? yeah there is no method overriding for static methods but could anyone please explain more the weird behavior of pc instance and why does it refer to the parent method even tho its pointing on the child class??
and why is it allowed to call a static method with a reference to an instance of the class ?
Thanks
There is no method overriding for static methods. The static type of the instance being used to call the method (ParentClass in your example) determines which method is called.
Besides that, it's bad practice to use an instance reference in order to call a static method. You should use ClassName.methodName() to execute a static method.

Categories

Resources