Skip to main content
gamedev.net
🔒 Locked

static inheritance in Java

Started by DevFred Mar 19, 2009 at 2:28 AM 0 replies 3.3k views
Original Post
DevFred
DevFred
class A
{
	public static void print()
	{
		System.out.println(A.class); // here
	}
}

class B extends A
{
}

public class Main
{
	public static void main(String[] args)
	{
		B.print();
	}
}
This prints "class A". Is there anything else I can write in the commented line that will make subclasses of A print their own class instead of A? I tried getClass(), but that doesn't work in a static context. My ultimate goal is a static method that reflects on subclasses.
Argus2
Argus2
Quote:
Original post by DevFred
This prints "class A". Is there anything else I can write in the commented line that will make subclasses of A print their own class instead of A? I tried getClass(), but that doesn't work in a static context.

My ultimate goal is a static method that reflects on subclasses.

I don't think you can do this with one "inherited" static method. A static method isn't really inherited in the way that instance methods are inherited, it's just for convenience that you can reference the static members of superclasses from a subclass.

So unless you shadowed class A's print() method with a static print() method in class B, you won't get any different behaviour out of it - the object that print() is being called on will always be the class object of A, and that object only contains the static members of class A.

I'm not sure what your goal is, that you can't use getClass() on instances where you need to. I believe best practice would expect that you always reference static members by [classname].[member], i.e. you should only call A.print() to avoid confusion.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.