I have the following problem in Java:
I have a base class and a derived class and I have a method in the base class. When I call the Base's foo method through Derived I want to get the Derived's class. The foo method can be generic if it can be done that way.
class Base
{
static void foo()
{
// I want to get Derived class here
// Derived.class
}
}
class Derived extends Base
{
}
Derived.foo();
Thanks for your help!
David
That's not the way that static methods work. You'll have to implement Derived.foo(), do whatever it is that's special to Derived, and that method then calls Base.foo(). If you really need the type information, you could create Base.foo0(Class klass).
But to be honest, any static method that needs to know that type of the class that it's invoked on should probably be an instance method.
Well, the caller of Derived.foo() knows what they are calling, so you could alter your methods thus:
class Base
{
static void foo(Class< T > calledBy)
{
// I want to get Derived class here
// Derived.class
}
}
class Derived extends Base
{
}
Derived.foo(Derived.class);
static methods are not inheritated. Static methods with the same signature can only hide similar methods in the superclass. This means that you never will see the result you probably want - you always exactly know the enclosing class. It is never possible that the static method is somehow "within" another class. So it is just impossible to produce the desired result. Calling a static method from a subclass or an instance is a bad idea for this reason as it just hides the real class. (IDEs and static code analysis tools can mark or correct this.)
Sources:
JLS http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#227961
http://docs.oracle.com/javase/tutorial/java/IandI/override.html
So what works with inherited methods does not work with static methods that are not inherited.
class Base {
static void foo() {
// Only the static context is available here so you can't get class dynamic class information
}
void bar() {
System.out.println(getClass());
}
}
class Derived extends Base {
}
class Another extends Base {
static void foo() {
// No super call possible!
// This method hides the static method in the super class, it does not override it.
}
void bar() {
super.bar();
}
}
Derived derived = new Derived();
derived.bar(); // "class Derived"
Base base = new Base();
base.bar(); // "class Base"
// These are only "shortcuts" for Base.foo() that all work...
derived.foo(); // non-static context
Derived.foo(); // could be hidden by a method with same signature in Derived
base.foo(); // non-static context
Base.foo(); // Correct way to call the method
Another a = new Another();
a.foo(); // non-static context
Another.foo();
Is it good idea that the language allows this? - Hm. I think it is telling that IDEs and code analysis tools warn and can even correct this automatically.
Not possible, Derived.foo() will simply give code for Base.foo().
Derived.foo();
This will go to foo defined in Derived, if one is defined there:
class Base {
static void foo() {
System.out.println("Base");
}
}
class Der extends Base {
static void foo() {
System.out.println("Der");
}
}
class Check {
public static void main(String[] args) {
Base.foo();
Der.foo();
}
}
When I run it:
javac -g Check.java && java Check
Base
Der
So what is your question? If you to require that each derived class implement foo that is not possible to enforce in Java.
Related
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.
When defining extra methods (that do not override the super class methods) in an Anonymous Inner Class the code compiles fine without any issues but if I try to call the extra method it throws an error. So is it only possible to override methods in the sub class when extending with an anonymous inner class? If it is so can anyone please explain me why?
Here's what my code looks like
class SomeClass {
public static void main(String[] args) {
SomeOtherClass a = new SomeOtherClass() {
#Override
public void methodFromSuperClass() {
System.out.println("Method from super class!");
}
public void subClassMethod() {
System.out.println("Sub class method");
}
};
a.methodFromSuperClass(); //This works fine
a.subClassMethod(); // But calling this extra method throws an error
}
}
This is the error that I'm getting
SomeClass.java:20: error: cannot find symbol
a.subClassMethod();
^
symbol: method subClassMethod()
location: variable a of type SomeOtherClass
1 error
This situation is exactly the same as if the anonymous class had a name:
class SomeOtherClass {
public void methodFromSuperClass() { }
}
class Subclass extends SomeOtherClass {
#Override
public void methodFromSuperClass() {
System.out.println("Method from super class!");
}
public void subClassMethod() {
System.out.println("Sub class method");
}
}
And you did:
SomeOtherClass a = new Subclass();
a.subClassMethod();
Wouldn't you agree that you shouldn't be able to call subClassMethod here? After all, the compiler knows that a is of type SomeOtherClass, but not which subclass of SomeOtherClass it is. It doesn't analyse your code that far back to see that you actually assigned an instance of Subclass to it.
The situation with anonymous classes is basically the same. It's just that this time, the subclass doesn't have a name in your code, but it's still a subclass, and the same reasoning that "the compiler doesn't analyse your code that far back" applies.
Since the anonymous subclass has no name, you can't do something like Subclass a = new Subclass(); as in the named subclass example, but since Java 10, you can do:
var a = new SomeOtherClass() { ... };
var lets the compiler infer the type of the variable for you without you saying the type name. The compiler will infer the anonymous subclass as the type for a, and this will allow you to do:
a.subClassMethod();
Finally, it is totally allowed to declare extra members in anonymous classes - it's just rather hard to access them from anywhere other than inside the anonymous class, or the local scope, because the anonymous class has no name. Declaring extra members is still sometimes useful though, because you can access them in the overridden methods for example.
Your assumption is correct. It is not possible to call the unoverridden method this way.
Consider an example where you have declared an interface and instantiated it with a concrete class, then you still only have access to the methods defined in the interface and not in the class.
public interface MyInterface{
public void someMethod();
}
public class MyImpl implements MyInterface{
//someMethod() implementation
// ...
// newMethod()
public void newMethod(){
//some implementation
}
}
public class Main{
public static void main(String[] args){
MyInterface inter = new MyImpl();
inter.someMethod(); // this call is ok
inter.newMethod(); // this call leads to a Symbol not found Exception,
// because MyInterface has no method named newMethod...
}
}
Hope it is now clearer what is meant by this
As shown in http://docs.oracle.com/javase/tutorial/java/IandI/override.html, Java does allow
Overriding an instance method by an instance method and
Hiding a static method by a static method
My question is why Java doesn't allow hiding a static superclass method by an instance method. This could be done like this:
class Base {
static void foo () {}
}
class Derived extends Base {
void foo () {}
void access () {
foo ();
Base.foo ();
}
}
I don't see any particular issue with the above approach - it is only as "messy/complex" as the (allowed) hiding of statics already is.
I suspect it is to avoid confusion with dealing with the base class. In fact I imagine the designers didn't see an obvious way this should behave.
class Base {
static void foo () {}
}
class Derived extends Base {
void foo () {} // say this compiled
}
Base b = new Derived()
b.foo(); // should the static or the virtual method be called?
Should b.foo() call Base.foo() or should it potentially call Derived.foo()?
Simple answer: that would be the mess.
Concrete answer: what to call in that case Derived.foo()? Base.foo() can't be called as it's hidden (as per you), Derived.foo() can't be called as it's not static.
Because, one are like Bananas and the other ones are Apples.
Explaination:
Static Methods are created when reading the Class-Structure
Methods are created when a object of a class is created.
Example:
Foo.bar();
is something different than
new Foo().bar();
Guess which one is called?
Foo f = new Foo();
f.bar();
Another to add here is:
1. Static methods belong at the class level. So u cannot override method in the derived class.
as simple its called hiding. :)
2. Instance methods belong to the objects, so objects are overrided. So we can override in the derived class.
Above other comments give a good example have a look into it..
Regards
Punith
I have the following classes.
public class Super{
public static void useSubClass(){
//I want to access the sub class object here, how.
}
}
public class Sub1 extends Super{
}
public class Sub2 extends Super{
}
I want to access the sub-class object from a static method in super-class. i.e. When I call Sub1.useSubClass() the method has access to Sub1.class and when I use Sub2.useSubClass(), I can access the Sub2.class.
Is there any way to access the sub-class object from super-class.
In general, you cannot do that from a superclass (and shouldn't!) because you won't know (and shouldn't assume anything about!) what classes will inherit from your superclass.
Depending on exactly what you want to do, there are alternatives, such as:
Use the template pattern to define "filler methods" that your subclasses must implement; these filler methods will be called by the template method in your superclass.
Define methods to be overridden by your subclass.
Define interfaces to be implemented by your subclass.
Update: As #JB Nizet has pointed out, I might have misread the question.
Here's something (very similar to the Observer Pattern) you can do if you wish to access subclasses from the static method in your superclass:
Define a static listener list in your superclass, call it List observerList
In the constructor of your superclass, add the class instance itself to that static observerList
For all subclasses, it is their responsibility to call super() from their constructors in order to register themselves to observerList (and unregister in deconstructor)
Then in your superclass's static useSubClass() method, you can iterate through that list of subclass instances, find the particular one you care about (maybe specified by some argument), and then do something with it.
Static methods are not inherited, and calling Sub2.useSubClass() is strictly equivalent to calling Super.useSubclass().
There is no way to get this information, because it doesn't exist. The compiler allows calling Sub2.useSubclass(), but translates it into Super.useSubclass().
public static void useSubClass(Super sub) {
if (sub instanceof Sub1) {
// Do something
} else if (sub instanceof Sub2) {
// Do something else
} else {
// Something else is extending Super
}
}
However, a better question is why? Can't you simply override the method in your subclass?
No you cannot because the super-class cannot know the methods of the sub-classes.
You should consider to create a new class which sees both super-class and sub-classes and implement the static method inside this new class
For the record, you could do this in Python, using class methods:
class super(object):
#classmethod
def usesubclass(cls):
print cls
class sub1(super):
pass
class sub2(super):
pass
Using this code, you could call sub1.usesubclass() or sub2.usesubclass(), and that would print the representations of the sub1 and sub2 classes, respectively:
>>> sub1.usesubclass()
<class '__main__.sub1'>
>>> sub2.usesubclass()
<class '__main__.sub2'>
Java, however, does not support such mechanisms, unfortunately. When you compile Sub1.useSubClass() in your example, the compiler will simply use Sub1 as the basic namespace to look up the the useSubClass() method in Super, but no information on that is actually compiled into code. In the resulting bytecode, the call is simply one directly to Super.useSubClass() and nothing more.
I sympathize with your plight, but Java is what it is. The closest thing you could come, I think, would be the following code:
public class Super {
public static <T extends Super> void useSubClass(Class<T> sub) {
}
}
And then call that method explicitly as either Super.useSubClass(Sub1.class) or Super.useSubClass(Sub2.class).
I figured something out. It works if implemented with care.
/** SuperClass.java **/
public abstract class SuperClass {
public static void printClass(){
System.out.println(new ImplementingClassRetriever().getCallingClass());
}
static class ImplementingClassRetriever extends SecurityManager{
public Class getCallingClass() {
Class[] classes = getClassContext();
for (Class clazz : classes) {
if (SuperClass.class.isAssignableFrom(clazz) && clazz != null
&& !clazz.equals(SuperClass.class)) {
return clazz;
}
}
return null;
}
}
}
/** Main.java **/
public class Main{
public static void main(String[] args) {
Sub.printClass(); //this does not work
Sub.testStaticCall(); //this works!! :)
}
}
class Sub extends SuperClass{
public static void testStaticCall(){
Sub.printClass(); //calling the method in the super class
}
}
This is just a toy example. The super class contains a static class that contains a method to retrieve the calling class.
In the subclass I have another static method which calls the superclass's method for printing the class name.
The Main class/function contains two calls to Sub's inherited and locally implemented method. The first call prints null, because the calling context (i.e. Main) is not a subclass of Super However the delegate method in Sub works because the calling context is now a subclass of SuperClass and hence the calling class can be determined.
Although You can create a reference to the super class and point it to any sub-class. This can also be done dynamically during run-time. This is a way of run-time polymorphism.
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.
//