0

I am trying to perform an example as told by some faculty but don't seem to understand how this code would work.

public class Child extends Base {


    void show() {
        System.out.println("Child");
    }


    void display(){
        System.out.println("Display");
    }

    public static void main(String[] args) {
        Base b=new Child();
        b.show();
        b.display();

    }
}

class Base  {

    void show() {
        System.out.println("Base");
    }
}

These two classes are in the same file can anyone please tell what is going on here as i am not able to understand.

$ javac Child.java
Child.java:20: error: cannot find symbol
          b.display();
           ^
  symbol:   method display()
  location: variable b of type Base
  1 error
Ray Toal
  • 86,166
  • 18
  • 182
  • 232
Abhishek Dubey
  • 937
  • 8
  • 11
  • 3
    `Base` has no `display()` method, so you can't call `b.display()`. If you cast `b` to `Child`, then you can call it as the reference is now of type `Child` which does have the method. – Kayaman Apr 19 '18 at 06:53
  • The class called base does not have a method called display() change the type on the left to Child – billy.mccarthy Apr 19 '18 at 06:53
  • Why is it necessary for the Base class to have the display method.What is the theory ?When show method is called the show method of Child class get invoked. – Abhishek Dubey Apr 19 '18 at 06:56
  • `Child` is the child of the `Base` class, child has implemented display method, but not base class, so you will be able to call display in child, but not in base class object, method show from base class should be accessible from child class. Its OOP principles – xxxvodnikxxx Apr 19 '18 at 06:57

1 Answers1

3

You define the variable b with a type Base. Base doesn't have a display method so it gives you an error. You assign a Child to b but the compiler doesn't know that specifically so gives you an error. b can be anything that is or extends Base and not necessarily have the display method.

If you know for sure that b is instance of child (which is the case in your code) you can cast it before using display. Like that:

((Child)b).display();
Veselin Davidov
  • 7,031
  • 1
  • 15
  • 23