If You Overwrite a Field in a Subclass of a Class, the Subclass Has Two Fields with the Same Name(And Different Type)

If you overwrite a field in a subclass of a class, the subclass has two fields with the same name(and different type)?

Member variables cannot be overridden like methods. The number variables in your classes Beta and Gama are hiding (not overriding) the member variable number of the superclass.

By casting you can access the hidden member in the superclass.

Wondering about the output of the following Java program

The output will be:

false
true

Because in your Subclass aVariable is false by default (so assignation aVariable = false; is needless). Read more about Primitive Data Types default values.

And in Superclass you initialize aVariable as true by invoking the superclass' method using the keyword super: super.aMethod();. Read more about Accessing Superclass Members.

Take a look on demo.

Why this is happening in Java?

Your question, specifically, seems to be "why does System.out.println(obj.x); print 10 and not 20?"

obj is declared as an A, and so obj.x will always resolve to the field x that exists within A. There is no dynamic dispatch for fields.

Ultimately, your problem is that there is no field overriding in Java. The field in the super class just gets hidden. When you declare

class A {
int x = 10;
}
class B extends A{
int x = 20;
}

and instantiate a B, the object that you get back actually contains two integers. The fact that they have the same name is basically incidental and just makes it slightly harder to refer to them independently, which is usually why you should just choose different names.

Java field inheritance and upcasting weird behaviour

You've came across the feature of Java called variable Hiding.
The field "i" in Derived hides the field "i" in class Base.

Unlike methods, the fields cannot be overridden in java, hence the behavior.

I've found a very in-depth tutorial on this topic that you might consider useful

java overriding static fields

It seems that you're confused with the concept of Overriding.

in Java, as far as class variables are concerned, you do not override them, you hide them.

Overriding is for instance methods. Hiding is for instance variables.

Both Hiding and Overriding are different.

Access overwritten fields of super class in Java?

The keyword super is most of the times used in conjunction to accessing superclass methods, most of the times a constructor from the parent class .

The keyword this is most of the times used to distinguish fields of the class from method parameters or local variables with the same name.

However, you can also use super to access fields of the superclass or this to call methods (which is redundant since all calls are virtual methods calls), or another constructor from the same class.

Here is an example of the usage for accessing fields.

public class Base {

public int a = 1;
protected int b = 2;
private int c = 3;

public Base(){

}
}

public class Extended extends Base{

public int a = 4;
protected int b = 5;
private int c = 6;

public Extended(){

}

public void print(){
//Fields from the superclass
System.out.println(super.a);
System.out.println(super.b);
System.out.println(super.c); // not possible

//Fields from the subclass
System.out.println(this.a);
System.out.println(this.b);
System.out.println(this.c);
}
}

public static void main(String[] args) {
Extended ext = new Extended();
ext.print();
}

You can always rename the fields in your subclasses not to conflict, but if you want to distinguish a method parameter or local variable from the superclass field, use super as you would use this

Can a child class overwrite a private field inherited from a superclass?

JavaScript does not support directly accessing private properties inherited from another class, which is how private members are supposed to work. You seem to want the functionality of protected properties. As of 2022, JavaScript does not support protected properties or members of any kind. Why that is, I can't imagine, since other OOP languages have allowed said functionality since time immemorial.

If you have control over the code of the parent class, you can simulate protected properties by using symbols.

const className = Symbol();

class Parent {
[className] = 'Parent'; // create protected [className]

getClassName() {
return this[className]; // return [className] from object
}
}

class Child extends Parent {
[className] = 'Child'; // re-define [className] for this child class
}

console.log(new Child().getClassName()); // --> this prints 'Child'

superclass attribute overrides subclass attribute

While fields can be shared within inheritance, given the right access modifiers (i.e. anything not private pretty much - default access will not work across different packages though), they are resolved at compile time, contrary to methods which are resolved at runtime (the latter is called virtual method invocation).

ints default to 0, and you're passing an A reference type, so A.cost's value of 0 is printed.

You have a range of options here:

  • Do not declare cost in B and assign cost value from A in B's constructor, or instance initializer, etc. to 10
  • An ugly, explicit cast in method4A, e.g. System.out.println(((B)a).cost);
  • Passing a B reference type instead of A in method4A
  • Keep both cost variables and declare a simple getter in A returning cost, and @Override it in B with the same implementation (it'll return B's cost even when invoked on a A reference if the instance actually is B)

Is there a way to override class variables in Java?

Yes. But as the variable is concerned it is overwrite (Giving new value to variable. Giving new definition to the function is Override). Just don't declare the variable but initialize (change) in the constructor or static block.

The value will get reflected when using in the blocks of parent class

if the variable is static then change the value during initialization itself with static block,

class Son extends Dad {
static {
me = "son";
}
}

or else change in constructor.

You can also change the value later in any blocks. It will get reflected in super class



Related Topics



Leave a reply



Submit