Inheritance assistance for method hiding and field hiding - java

public class Test
{
static int i = 1;
static void m1()
{
}
}
class Test1 extends Test
{
int i = 1; //allowed
void m1() // not allowed; Both are instance level, so why this difference? Both can be accessed with super keyword
{
}
}
Why can't the static method be hidden with the same signature, but the static field is allowed to do this? Both are instance level, so why is only the static field allowed?

m1() in class Test is a static method, while m1() in Test1 is non static. Now imagine if this would have been allowed then which implementation would be picked by runtime when you execute below statement:
new Test1().m1();
Since instance of child class (Test1 in your case) can access also access static method from parent class (from Test). That is why it is not allowed.
For you next question why variable with same name is allowed in Test1: parent class' static variable can not be accessed from child class instance. In other words parent class' static state is hidden from child. That is
Test1.i; // compilation error, can't access parent's static variable
will result in compilation error. And if you try
new Test1().i; // will access Test1's i variable
it will point to the child class' state not parent's. That is why child class can have variable with the same name.
Note: If i in Test was non-static, even in that case Test1 can have variable with name i. In this case i in Test1 will shadow i in Test.
EDIT
From Shahaan Syed's comment:
new Test1().i; why is this allowed is my concerned
To put Shahaan Syed's confusion in another words: Why
in case of variable, child class can have a non-static variable while
parent class has a static variable with the same name,
on the other hand, child class can not have a non-static method when
parent class has a static method with the same name?
As Kevin Esche commented, I also think that Java messed up somewhere by allowing access to static methods of parent class from instance of child class. Though it is not a good practice and compiler generates warning as well.
Here's a quote from (JLS §8.3):
In this respect, hiding of fields differs from hiding of methods
(§8.4.8.3), for there is no distinction drawn between static and
non-static fields in field hiding whereas a distinction is drawn
between static and non-static methods in method hiding.
But I could not find any reasoning behind this in JLS.
I think instead of generating warning there should have been compile time error. That is accessing both static field and static method of parent class from child class instance, should have been compiler error. In this respect things would have been consistent and easy to understand. But again it's just my thought.
Another interesting question on the same line: Why isn't calling a static method by way of an instance an error for the Java compiler?

Related

static and instance method in java -Parent and Sub class

Why cant we declare an instance method in sub Class B which shares the same signature of a static method in parent Class A?
It throws a compile time error if i try to do that.
My question is, since static method of parent class is restricted to parent class, why does instance method of child class does not compile.
Lets see by code:
`
public class A{
static void testStatic(){}
}
public class B extends A{
void testStatic (){}
}
public class Test{
public static void main (String[] args){
A a = new B()
a.testStatic();
}
`
In the above code,since A does not have an instance method by that name, and since Java allows static methods to be accessed by objects, Object a of type 'A' pointing to 'B' can call static method present in it(class A). But complier throws an error "The instance method cannot override a static method" why?
Note: I can understand if a class does not allow same method name for two methods, even if one is instance and other is static. But I fail to understand why it does not allow a sub class to have an instance of same name. Especially considering the fact that static methods cannot be overridden. And yet, Java allows subclass to have same name as parent class static method, which is called information hiding, but not overriding.
The compiler throws an error because those are the rules of the language. From the Java Language Specification §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.
(emphasis in the original). The language is dense (as in most places in the JLS) but it matches the situation you are describing. The JLS doesn't provide a rationale for this rule that I could find on first reading. But a little thought about how one might try to make this rule unnecessary shows why it's there.
It's illegal in Java. The call to the static method is allowed on an instance as well, so there'd be no way to distinguish which method to call in some cases:
A a = new A ();
B b = new B ();
A.testStatic (); // ok
B.testStatic (); // ok
a.testStatic (); // ok calling static
b.testStatic (); // undefined. What to call? Based on what?
Last call is the reason why it's not allowed.
Calls to static methods are resolved at compile time itself. So, they cannot be overridden. And by defining another method with the same signature as the static method, the compiler complains.
static method is bound with class whereas instance method is bound with object.
Static belongs to class area and instance belongs to heap area.
I am not hundred percent sure but I guess answer as below.
Static method means it can be used without an instance of the the class in which it is defined. Also static method can access only static variables of the class. Now if we override non static method and create an instance of sub class with reference of the super class, compiler will be confused for above two basic functioning of static method. Please debate if any thing wrong in this.
4 line showing error. so do this
public class B extends A

Why is a subclass' static initializer not invoked when a static method declared in its superclass is invoked on the subclass?

Given the following classes:
public abstract class Super {
protected static Object staticVar;
protected static void staticMethod() {
System.out.println( staticVar );
}
}
public class Sub extends Super {
static {
staticVar = new Object();
}
// Declaring a method with the same signature here,
// thus hiding Super.staticMethod(), avoids staticVar being null
/*
public static void staticMethod() {
Super.staticMethod();
}
*/
}
public class UserClass {
public static void main( String[] args ) {
new UserClass().method();
}
void method() {
Sub.staticMethod(); // prints "null"
}
}
I'm not targeting at answers like "Because it's specified like this in the JLS.". I know it is, since JLS, 12.4.1 When Initialization Occurs reads just:
A class or interface type T will be initialized immediately before the first occurrence of any one of the following:
...
T is a class and a static method declared by T is invoked.
...
I'm interested in whether there is a good reason why there is not a sentence like:
T is a subclass of S and a static method declared by S is invoked on T.
Be careful in your title, static fields and methods are NOT inherited. This means that when you comment staticMethod() in Sub , Sub.staticMethod() actually calls Super.staticMethod() then Sub static initializer is not executed.
However, the question is more interesting than I thought at the first sight : in my point of view, this shouldn't compile without a warning, just like when one calls a static method on an instance of the class.
EDIT: As #GeroldBroser pointed it, the first statement of this answer is wrong. Static methods are inherited as well but never overriden, simply hidden. I'm leaving the answer as is for history.
I think it has to do with this part of the jvm spec:
Each frame (§2.6) contains a reference to the run-time constant pool (§2.5.5) for the type of the current method to support dynamic linking of the method code. The class file code for a method refers to methods to be invoked and variables to be accessed via symbolic references. Dynamic linking translates these symbolic method references into concrete method references, loading classes as necessary to resolve as-yet-undefined symbols, and translates variable accesses into appropriate offsets in storage structures associated with the run-time location of these variables.
This late binding of the methods and variables makes changes in other classes that a method uses less likely to break this code.
In chapter 5 in the jvm spec they also mention:
A class or interface C may be initialized, among other things, as a result of:
The execution of any one of the Java Virtual Machine instructions new, getstatic, putstatic, or invokestatic that references C (§new, §getstatic, §putstatic, §invokestatic). These instructions reference a class or interface directly or indirectly through either a field reference or a method reference.
...
Upon execution of a getstatic, putstatic, or invokestatic instruction, the class or interface that declared the resolved field or method is initialized if it has not been initialized already.
It seems to me the first bit of documentation states that any symbolic reference is simply resolved and invoked without regard as to where it came from. This documentation about method resolution has the following to say about that:
[M]ethod resolution attempts to locate the referenced method in C and its superclasses:
If C declares exactly one method with the name specified by the method reference, and the declaration is a signature polymorphic method (§2.9), then method lookup succeeds. All the class names mentioned in the descriptor are resolved (§5.4.3.1).
The resolved method is the signature polymorphic method declaration. It is not necessary for C to declare a method with the descriptor specified by the method reference.
Otherwise, if C declares a method with the name and descriptor specified by the method reference, method lookup succeeds.
Otherwise, if C has a superclass, step 2 of method resolution is recursively invoked on the direct superclass of C.
So the fact that it's called from a subclass seems to simply be ignored. Why do it this way? In the documentation you provided they say:
The intent is that a class or interface type has a set of initializers that put it in a consistent state, and that this state is the first state that is observed by other classes.
In your example, you alter the state of Super when Sub is statically initialized. If initialization happened when you called Sub.staticMethod you would get different behavior for what the jvm considers the same method. This might be the inconsistency they were talking about avoiding.
Also, here's some of the decompiled class file code that executes staticMethod, showing use of invokestatic:
Constant pool:
...
#2 = Methodref #18.#19 // Sub.staticMethod:()V
...
Code:
stack=0, locals=1, args_size=1
0: invokestatic #2 // Method Sub.staticMethod:()V
3: return
The JLS is specifically allowing the JVM to avoid loading the Sub class, it's in the section quoted in the question:
A reference to a static field (§8.3.1.1) causes initialization of only the class or interface that actually declares it, even though it might be referred to through the name of a subclass, a subinterface, or a class that implements an interface.
The reason is to avoid having the JVM load classes unnecessarily. Initializing static variables is not an issue because they are not getting referenced anyway.
The reason is quite simple: for JVM not to do extra work prematurely (Java is lazy in its nature).
Whether you write Super.staticMethod() or Sub.staticMethod(), the same implementation is called. And this parent's implementation typically does not depend on subclasses. Static methods of Super are not supposed to access members of Sub, so what's the point in initializing Sub then?
Your example seems to be artificial and not well-designed.
Making subclass rewrite static fields of superclass does not sound like a good idea. In this case an outcome of Super's methods will depend on which class is touched first. This also makes hard to have multiple children of Super with their own behavior. To cut it short, static members are not for polymorphism - that's what OOP principles say.
According to this article, when you call static method or use static filed of a class, only that class will be initialized.
Here is the example screen shot.
for some reason jvm think that static block is no good, and its not executed
I believe, it is because you are not using any methods for subclass, so jvm sees no reason to "init" the class itself, the method call is statically bound to parent at compile time - there is late binding for static methods
http://ideone.com/pUyVj4
static {
System.out.println("init");
staticVar = new Object();
}
Add some other method, and call it before the sub
Sub.someOtherMethod();
new UsersClass().method();
or do explicit Class.forName("Sub");
Class.forName("Sub");
new UsersClass().method();
When static block is executed Static Initializers
A static initializer declared in a class is executed when the class is initialized
when you call Sub.staticMethod(); that means class in not initialized.Your are just refernce
When a class is initialized
When a Class is initialized in Java After class loading, initialization of class takes place which means initializing all static members of class. A Class is initialized in Java when :
1) an Instance of class is created using either new() keyword or using reflection using class.forName(), which may throw ClassNotFoundException in Java.
2) an static method of Class is invoked.
3) an static field of Class is assigned.
4) an static field of class is used which is not a constant variable.
5) if Class is a top level class and an assert statement lexically nested within class is executed.
When a class is loaded and initialized in JVM - Java
that's why your getting null(default value of instance variable).
public class Sub extends Super {
static {
staticVar = new Object();
}
public static void staticMethod() {
Super.staticMethod();
}
}
in this case class is initialize and you get hashcode of new object().If you do not override staticMethod() means your referring super class method
and Sub class is not initialized.

Concepts in Inheriting a Static method

I have 2 classes as below
public class statictest {
public void print()
{
System.out.println("first one");
}
}
public class newer extends statictest
{
public void print()
{
System.out.println("second one");
}
}
and in the main function I do
statictest temp = new newer();
newer temp2 = new newer();
temp.print();
temp2.print();
Output is :
second one
second one
But When I make these 2 methods static the output is
firstone
secondone
what happened to late binding in this case?? Can anyone explain
This is called dynamic method invocation. You can look on this JLS.
It states,
The strategy for method lookup depends on the invocation mode.
If the invocation mode is static, no target reference is needed and
overriding is not allowed. Method m of class T is the one to be
invoked.
Otherwise, an instance method is to be invoked and there is a target
reference. If the target reference is null, a NullPointerException is
thrown at this point. Otherwise, the target reference is said to refer
to a target object and will be used as the value of the keyword this
in the invoked method. The other four possibilities for the invocation
mode are then considered.
static methods can not be overridden, they remains hidden if redefined in subclasses.
Ps: they do take part in inheritance. you can access static methods, from subclass name.
It is because static methods are not polymorphic. Static methods will not be Overridden.
Do search on Dynamic method dispatch
Static methods can't be overridden, that is why after making it static you are getting output like this.
static methods can not overridden.
you created object for newer class by using statictest class reference variable temp2 u hold that object by using super class reference variable. At the time of compilation compiler just checks syntax weather that method is available in the statictest class or not.if it is available it complies fine otherwise error will come.your code you declared static print method so it is availble in statictest class compilation done fine but your method is static it can't be override. now coming main method u declared
statictest temp = new newer();
now temp object is created with statictest class features only. it won't contains newer class methods or variables object is created based on the referenced class properties only it won't contains subclass properties(newer class) if super class(statictest) contains any non static values same as sub class(newer class) just it will overrides super class properties. why it overrides? because with the class it will not allow to declare same varibles or same methods

I dont understand this inheritance functionality

Consider the following illegal code :-
class WrongCode{
int i;
static int i;
}
Here, the compiler says that we have duplicate fields in the same class.
Now, consider the following classes in the same file.
class Parent{
int i = 10;
}
class Child extends Parent{
static int i = 100;
}
public class Main{
public static void main(String ... aaa){
Parent ob = new Child();
System.out.println(ob.i); // This prints Parent's i
}
}
Since the actual object is of Child, shouldn't ob refer to Child's i? And if it is refering to Parent's "i", then in a way it is also having Parent's "i" in its own class along with its own static "i" which is NOT ALLOWED.
Child static i overshadows Parent i. And Parent's i is not static, so then how is it accessed directly using instance and not className?
You have instance field i in Parent class and it remain an instance field in Child class.
System.out.println(ob.i); // must be 10
Have a look at - Oracle Java Tutorial - Hiding Fields
It is important to realize here that there is no way System.out.println(ob.i); could print Child's i: it only knows that ob is of declared type Parent, not that it was instantiated with an actual Child. Thus, if Parent did not have any i, there would be a compile error. If parent has an i, this is printed.
I have seen it mentioned on SO that access of class variables via instances (i.e. ob.i being equivalent to Parent.i) should be considered a serious design flaw of Java. I agree it can be sometimes confusing. Anyway, both your parent and child could also have a non-static i and it need not be the same. The argument above should be applicable to reasoning which one would be printed in which situation.
In ob, the static int i of child is never visible since ob is of type Parent, irrespective of how it was instantiated( base class or derived class).
That's why you have the value as 10, that Parents i value.
When you access class member fields (instance variables) like ob.i. you'll get the results from the class that's known at compile time, not what is known at run time. Thats why you have value as 10 which is parents value.
For method calls they are dispatched at run time to an object of the actual class the reference points.
Regarding shadowing here is what Java lang spec says:
If the class declares a field with a certain name, then the declaration of that field is said to hide any and all accessible declarations of fields with the same name in superclasses, and superinterfaces of the class.
A hidden field can be accessed by using a qualified name (if it is static)
language spec
You may refer "Field Declarations" section.
Actually its polymorphism and ob have access only to parent class fields and behaviuors if any...
Java lets your class have its own variables that have the same name as a variable in the parent. But it can't just let you randomly redefine parent variables, as that would cause other stuff to break. So what it does...when you have a variable obj that's declared as the parent class, even if it holds an instance of a child class, obj.i will refer to the parent class's i rather than the child's.

about non-static class in java

My doubt is when I run the following program
public class NonStatic
{
class a
{
static int b;
}
}
The compiler is giving a error that "inner classes cannot have static declarations"
ok,then I made a change instead of "static int b" to "final static int b" its giving
same error but when I wrote "final static int b=10" means with initialization compiler
didn't complain,please can any body explain this what's the concept behind this.
it is so by design, just see the Java Language Specification: Inner Classes and Enclosing Instances
An inner class is a nested class that is not explicitly or implicitly declared static. [...] Inner classes may not declare static members, unless they are compile-time constant fields (§15.28).
final static int b=10
Is interpreted as a constant so compiler can just inline it. Similarly you can have static final constants in interface.
final static int b
Is missing initialization,which is required for final member, so compiler can't quite figure what you want.
Try putting following block right after it out of curiosity:
static {
b=10;
}
Although it probably would not work...
If a field is static, there is only one copy for the entire class, rather than one copy for each instance of the class
A final field is like a constant: once it has been given a value, it cannot be assigned to again. hence when we r using final we have to assign the value to the variable.
have a look at the following link
Here is my take on this issue.
Inner class is defined as a not static member of outer class and hence, it's instance cannot exist without the instance of outer class.
The static fields of a class are accessible without creating an instance of that class.
Now if you add a static field in the inner class, that means you can access that field without create the instance of inner class BUT according to #1 instance of inner cannot exist without an instance of outer class. So this is the conflict and hence the error.
TO CROSSCHECK : Just declare the inner class static and it will correct the error.
Its because a final static variable is a constant meaning it can't change at run time, while a static variable is not a constant and can change during runtime.
So in a class static variables aren't allowed in an inner class but the constants(final) are allowed.

Categories