-1

I have a parent class A which has a primitive type property x

public class A {
    String type = "A";
    int x = 5 ;
    void increment()
    {
        x++ ;
        System.out.println(x);
    }
}

I have a child class B which extends from class A, This child class also has propery x of String type

public class B extends A {
     String type = "B" ;
     String x = "Hello";
}

Now, both parent and child class has instance variable x with different type( int and String).

Parent class A has a method to increase value of X and now the method is available in the child class B ( Class B extends Class A, so all the methods in class A are accessible in class B)

Now I have a main method in a Runner class,

public class Runnable {
     public static void main(String[] args) 
     {
          //Creating object
          B instanceOfB = new B() ;
          //Invoke increment method
          instanceOfB.increment();
     }
 }

While running the main method, I got an OUTPUT : 6

I am invoking increment method using reference variable instanceOfB

instanceOfB.increment();

instanceOfB is an instance of Class B.

By invoking this function, we are trying to increase the value stored in variable x, but x has reference to a String Object.

It should either throws compile time reception or run time exception because we are trying to increase a String object, It is not possible but I got output 6.

  • Why did you expect an exception? In the code you posted B does not override the increment() method, so the implementation of A will be called. And A does not know anything of its subclass B or its fields, so it will just do what it always does. What did you expect to happen? – OH GOD SPIDERS Oct 07 '21 at 12:12
  • 1
    I can see why you might expect a compile error from having two fields with the same name; but it certainly would not compile and then produce an exception. – khelwood Oct 07 '21 at 12:14
  • Maybe to clear up the confusion a bit: Fields (Variables) are not overridden like methods, if they have the same name they are just "shadowed". But your instances of class `B` will internally have 2 fields `int x = 5;` and `String x = "Hello";` So your instances of `B` still have that int value and that is used in the increment method. – OH GOD SPIDERS Oct 07 '21 at 12:17
  • 1
    Does this answer your question? [Hiding Fields in Java Inheritance](https://stackoverflow.com/questions/12244670/hiding-fields-in-java-inheritance) – jsheeran Oct 07 '21 at 12:20

1 Answers1

1

The behavior of instance variables and instance methods in a class hierarchy is different. If you wanted to access the value in the subclass from the superclass, you would need to wrap the subclass value with an instance method that is declared in the superclass but overridden in the subclass.

Benjamin Berman
  • 521
  • 4
  • 15