3

I was told that static methods in java didn't have Inheritance but when I try the following test

package test1; public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { TB.ttt(); TB.ttt2(); } } 

package test1; public class TA { static public Boolean ttt() { System.out.println("TestInheritenceA"); return true; } static public String test ="ClassA"; } 

package test1; public class TB extends TA{ static public void ttt2(){ System.out.println(test); } } 

it printed :

TestInheritenceA ClassA

so do java static methods (and fields) have inheritance (if you try to call a class method does it go along the inheritance chain looking for class methods). Was this ever not the case? And are there any inheritance OO languages that are messed up like that for class methods?


So apparently static methods are inherited but can't be overidden, so does c# share that problem? Do any other Languages?

3 Answers 3

5

In Java, fields and static methods are inherited, but cannot be overridden - I believe that is what whoever told you that "they are not inherited" meant.

Non-private, non-static methods are inherited and can be overridden.

Sign up to request clarification or add additional context in comments.

2 Comments

Add also "non-final" to the answer :)
I totally forgot this question and made the same mistake discussing java on irc a few days ago.
3

This was always the case, but you cannot override class methods:

class A { public static void a() { system.out.println("A"); } } class B { public static void a() { system.out.println("B"); } } A a = new A(); a.a(); // "A" B b = new B(); b.a() // "B" a = b; a.a(); // "A" 

1 Comment

If B would not extend A, the assignment would not work and the whole question would be meaningless ... :D
0

That's the meaning of static. It means per class. Static fields and methods are shared among instances. If you change a static value, it's reflected across instances.

2 Comments

Methods always shared between instances, no matter weather they are marked as static or not. kindly change the statement.
I have mentioned static value. Methods are behavior.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.