I don't know if this question is valid or I am doing something wrong with defining the parent class structure.
But the following are the formation of the classes and interface are.
public interface Test {
public void print();
public void write();
}
class Parent implements Test{
@Override
public void print() {
System.out.print("This is parent class");
}
@Override
public void write() {
System.out.print("This is write method in parent class");
}
}
class Child extends Parent{
@Override
public void print(){
System.out.print("This is child class);
}
}
Expected output when I call method using the interface
Test test = new Parent();
test.print();
It should call print method from the Child class.
And when I call method using interface
Test test = new Parent();
test.write();
It should call write method from the Parent class.
So right now it's not happening, in both the cases it's calling the method from the Parent class.
So any suggestion or answer are much appreciated.
By using:
Test test = new Parent();
test.write();
your test
is of type Parent
and is unaware of Child
. Hence your output indicates both methods on the Parent
class are called.
Try:
Test test = new Child();
test.print(); // Will call Child::print()
test.write(); // Will call Parent::write()
and you should achieve what you want.
N.B. For this to work, you must add write()
to your Test
interface, thus:
public interface Test {
public void print();
public void write(); // This is required for it to be accessible via the interface
}