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.
Related
This question already has answers here:
Are static methods inherited in Java?
(15 answers)
Closed 4 years ago.
From what I understand, usually the static method should be called using class's reference or it can be called directly without reference if its in a static method or static block.
But does this apply when static method is called from child class static blocks?
Why it allows such thing, as static methods are not inherited, it should only be allowed using parent class name right?
public abstract class abs {
/**
* #param args
*/
abstract void m();
static void n(){
System.out.println("satic method");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
class myclass extends abs{
#Override
void m() {
// TODO Auto-generated method stub
}
static{
n();
}
}
Why my child class static block can call parent class static method without reference or classname?
Static method n() is inherited by subclass myclass, so you can call it directly in the static block of myclass.
Usually the static method should be called using class's reference or
it can be called directly without reference if its in a static method
or static block.
Not really. For example an instance method can invoke a static method without prefixing the class.
More generally, static members (fields as methods) have to be invoked by prefixing their class only as the compiler cannot infer the class where they belong to.
As you invoke a static method defined in the parent class from a subclass (and static methods are inherited in the subclasses), you don't need to prefix the class of the method invocation as the compiler infer that.
Because you inherited the parent class, you have access to all non private members of that class directly as if it belonged to the child class.
Why it allows such thing
By inheritance.
as static methods are not inherited
You keep saying that. You're mistaken. From JLS #8.4.8:
A class C inherits from its direct superclass all concrete methods m (both static and instance) of the superclass for which all of the following are true: ...
For continuation see here.
All the members of superclass are inherited by subclass, which includes static methods too.
class SuperClassA {
static void superclassmethod() {
System.out.println("superclassmethod in Superclass ");
}
}
public class SubClassA extends SuperClassA {
static {
superclassmethod();
}
public static void main(String[] args) {
}
}
But when a static method of superclass is override it hides the superclass static method not overrides it.
Am not asking about difference between interface and abstract class.
It is working success individually, right?
interface Inter {
public void fun();
}
abstract class Am {
public static void fun() {
System.out.println("Abc");
}
}
public class Ov extends Am implements Inter {
public static void main(String[] args) {
Am.fun();
}
}
Why is it getting a conflict?
A static and non static method can't have the same signature in the same class. This is because you can access both a static and non static method using a reference and the compiler will not be able to decide whether you mean to call the static method or the non static method.
Consider the following code for example :
Ov ov = new Ov();
ov.fun(); //compiler doesn't know whether to call the static or the non static fun method.
The reason why Java may allow a static method to be called using a reference is to allow developers to change a static method to a non static method seamlessly.
We have to write our code so that it is syntax wise correct. Also equally important is to understand that our code does not puts any ambiguity for the compiler. In case we have any such ambiguity, the language designers have taken care to not allow the such code to compile.
A class inherits the behaviours from its super class. Static methods can be accessed from simply using class name and also from the instance. Suppose there is method with same name and signature (except for the static keyword), invoking the method on the instance will leave the compiler go for a toss. How will it decide what the programmer intents to do, whcih of the two methods he or she intends to invoke ?. Hence the language designers decided to have this case result in a compile error.
As per
http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.8.2
If a class C declares or inherits a static method m, then m is said to hide any method m', where the signature of m is a subsignature (§8.4.2) of the signature of m', in the superclasses and superinterfaces of C that would otherwise be accessible to code in C.
It is a compile-time error if a static method hides an instance method.
public class Ov extends Am implements Inter {
public static void main(String[] args) {
Ov.fun(); //static method is intended to call, fun is allowed to be invoked from sub class.
Ov obj = new Ov();
obj.fun(); //** now this is ambiguity, static method can
//be invoked using an instance, but as there is
//an instance method also hence this line is ambiguous and hence this scenario results in compile time error.**
}
}
In Java Programming, Can we call a static method of an abstract class?
Yes I know we can't use static with a method of an abstract class. but I want to know why.. ?
In Java you can have a static method in an abstract class:
abstract class Foo {
static void bar() { }
}
This is allowed because that method can be called directly, even if you do not have an instance of the abstract class:
Foo.bar();
However, for the same reason, you can't declare a static method to be abstract. Normally, the compiler can guarantee that an abstract method will have a real implementation any time that it is called, because you can't create an instance of an abstract class. But since a static method can be called directly, making it abstract would make it possible to call an undefined method.
abstract class Foo {
abstract static void bar();
}
// Calling a method with no body!
Foo.bar();
In an interface, all methods are implicitly abstract. This is why an interface cannot declare a static method. (There's no architectural reason why an interface couldn't have a static method, but I suspect the writers of the JLS felt that that would encourage misuse of interfaces)
If you are talking about java, answer is Yes But you need to define the static method. You cannot create an abstract static method. What you can create is non abstract static method.
Reason is you do not need a object instance to access a static method, so you need the method to be defined with a certain functionality.
so you cannot have,
abstract class AbstractClassExample{
abstract static void method();
}
But you can have,
abstract class AbstractClassExample{
static void method(){}
}
Hope this helps...
Here is a simple explanation.Abstract methods must be implemented later.We know that static methods cannot be overridden because static methods do not belong to any particular instance, rather it belongs to the class.Then different implementation of abstract method,which is static, in different classes is counter-intuitive.
Yes, of course you can define the static method in abstract class.
you can call that static method by using abstract class,or by using child class who extends the abstract class.Also you can able to call static method through child class instance/object.
To illustrate further test following example.
//Parent class
public abstract class TestAbstractClass {
static void testStaticMethod(){
System.out.println("In Parent class static method");
}
}
//child class
public class ChildClass extends TestAbstractClass {
public static void main(String[] args) {
TestAbstractClass parentObj = new ChildClass();
parentObj .testStaticMethod();
ChildClass childObj = new ChildClass();
childObj.testStaticMethod();
TestAbstractClass.testStaticMethod();
childClass.testStaticMethod();
}
}
From Java 9 onwards you can have static methods in an interface. However, the implementation must be provided in the block itself. Unlike static methods in a class, a static method in an interface is not inherited by implementation through a class or subinterface.
An abstract can contain a static method. It is because a static method though not overridden can be hidden.
But an abstract method cannot be declared static at the same time as an abstract method must be overridden ans implemented by a subclass's method and declaring it static will prevent overriding.
In other words, you cannot use abstract and static keywords to declare the same method. However, you can have a static method inside an abstract class.
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()