Hello all,
After reading the frist 2 chapters of
SCJP Sun Certified Programmer for
Java 5 Study Guide (Exam 310-055) by Katherine Sierra and Bert Bates, I have a question on inheriting public variables. This is my own question, based on what I understood in the first two chapters.
class A{
public int variableA=10;
public float variableB=15;
}
class B extends A{
public boolean variableA= false;
}
class TestVariableInheritance{
static public void main(
String[] args){
A arefb = new B();
System.out.println( " variableA from class A is : " + arefb.variableA );
//Polymorphism works only on instance methods, not instance variables
//The above should print 10 . no problem.
B onlyb = new B();
System.out.println( " inherited (not overridden) variableB in class B is " + onlyb.variableB );
}
}
1) variableB is inherited in class B , for this reason onlyb.variableB prints a value.
2) Similarly I expect variableA to also be inherited in class B , however
I am able to define a new variable with the same name variableA , but with a different type ( the type is changed from int to boolean)
The compiler allows me to change the type of the inherited variableA to anything, why?
I was expecting the compilation to fail, but why does the above code compile?
[ December 11, 2008: Message edited by: Rashmi Jaik ]