In java only methods are overridden, not variables. So, parent classe's variables won't be overridden by child's classes variable. It's a design decision in java. And one of the concern is that the parent classes methods can perform without worrying about child's classes variables...i.e. it helps in not breaking parent classes code
...
An example could be like below:
public class Parent {
String someVar; // note this: it is "String" type
String getSomeVar() {
}
}
public class Child extends Parent {
int someVar; // same name but different type, this would break the code if
// java permit "variable overriding" feature
}
You can clearly see that parent's type and child's type are different. I guess, you can understand now why variable overriding would be dangerous...
Update:
@helloWorld, After reading the last comment you've made, it looks like, you're misunderstanding the idea of overriding
.
Specially, I've prepared an example for you. Read the following code with comments:
class A {
public int a = 10;
public void show () {
System.out.println("Inside A: " + this.a);
}
}
class B extends A {
public int a = 20;
public int b = 10;
@Override
public void show() {
System.out.println("Inside B: " + this.a);
}
}
B b = new B();
A a = b;
b.show(); // prints "Inside B: 20", it should print "20", so it's okay
a.show(); // prints "Inside B: 20", so, method in 'A' is overrided by class 'B', cause, in normal definition it should print "10"
System.out.println("value of b.a: " + b.a); // prints "value of b.a: 20", it should print '20', so it's okay
System.out.println("value of a.a: " + a.a); // prints "value of a.a: 10", it is not overrided by class 'B', but notice 'a.show()' method was overrided
So, I guess, you've understood, that overriding means: when use something(a method/variable)
by parent/super class's reference
but get the behavior defined in child class's
while parent/super
class's implementation of that particular method/variable
is present, is known as overriding...
You may also read this.
And about this
:
this
is bound to an object
. And it's always used to access
only that particular class's scope
i.e. the variables/methods
declared in that class
. So, to access parent
within child
you need to use super
.