Hi Trung Hieu Hoang,
First of all, a warm welcome to CodeRanch!
Trung Hieu Hoang wrote:Static method in ParentClass supposes to stick to parent class and have nothing to do in ChildClass. But why is it now allowed?
Can you explain the reason behind?
Tryin to explain it using my own words and maybe even a code snippet (or two).
First of all, class (
static) methods are related to classes (hence their name) and instance methods are related to objects/instances (again hence their name
). Instance methods can be overridden (which is called
polymorphism), class (
static) methods can't. To invoke an instance method, you must have an instance. If you don't have an instance, you can't invoke an instance method. A class (
static) method can be invoked without having an instance, you just use the class name. But (although not recommended) you can also invoke a class (
static) method using an instance of this class. Let's illustrate with a code snippet
If you execute this code snippet,
"I'm static Joey!" will be printed twice.
If you look closely at
line1 in the above code snippet, this statement looks exactly the same as invoking an instance method. So assume it would be allowed to have a class (
static) method and an instance method with exactly the
same signature as illustrated in this code example
Because a class (
static) and instance method have exactly the
same signature, it's impossible to determine which method to execute on
line1. Therefore it's not allowed to have a class (
static) and instance method with exactly the
same signature. And the same reason applies to a superclass and subclass. Keep in mind that if the class (
static) method in the superclass is not visible to the subclass (e.g.
private), the subclass can have an instance method with the
same signatureThis code snippet will compile successfully (without any errors) and when executed the output will be:
I'm static Human!
I'm instance Joey!
And finally, please note that you can have a class (
static) and instance method with the same name but with a different parameter list. So the method signature of both methods must be different. Here's another code snippet to illustrate
The output of this code snippet is exactly the same as the previous one
Hope it helps!
Kind regards,
Roel