-1

I am getting error while accessing Child class method by using Parent class reference variable. Please help me.

How can I access that method?

class Parent 
{
    public void show()
    {
        System.out.println("Show method in Parent class");
    }
}
class Child extends Parent
{
    public void print()
    {
        System.out.println("Print method in Child class");
    }
}
public class Downcast
{
    public static void main(String args[])
    {
        Parent p1=new Child();
        p1.print();//showing error here
    }
}
baitmbarek
  • 2,440
  • 4
  • 18
  • 26

3 Answers3

1

Your Parent class knows nothing about methods in your Child class. That's why you get error.

One of the possible solutions is to make your Parent class as abstract and add abstract print() method in it, but in this case all subclasses should override this method:

abstract class Parent {

    public void show() {
        System.out.println("Show method in Parent class");
    }

    public abstract void print();
}

class Child extends Parent {

    @Override
    public void print() {
        System.out.println("Print method in Child class");
    }

}

public class Downcast {

    public static void main(String[] args) {
        Parent p1 = new Child();
        p1.print();
    }

}
0

The error is caused since the Parent class knows nothing about the Child class. One way to fix the error is by doing an explicit cast ((Child) p1).print();

-1

You can do a cast :

class Parent 
{
    public void show()
    {
        System.out.println("Show method in Parent class");
    }
}
class Child extends Parent
{
    public void print()
    {
        System.out.println("Print method in Child class");
    }
}
public class Downcast
{
    public static void main(String args[])
    {
        Parent p1=new Child();
        ((Child) p1).print();// Out : Print method in Child class
    }
}
DLx
  • 97
  • 1
  • 13