Okay so I made two classes parent and child , child extends parent they both have a function called print. Child class however have two print functions one is parameterized and other one is not (overloading print function in child class).
parent class has only one print function.
Now when i made a object like this
parent p = new child();
it is giving compile error but it should not and i dont know why ?
code snippet :
class temp {
public static void main(String[] args) {
try {
parent p = new child();
p.print();
p.print(1);
}catch (Exception e){
System.out.println(e.getStackTrace());
}
}
}
class parent {
void print() {
System.out.println("parent print function");
}
}
class child extends parent {
void print() {
System.out.println("child print function");
}
void print(int i) {
System.out.println("child parameterized print function");
}
}
Now since child is inheriting parent both their contructors will be called but eventually the object that is being created is a child class object , so it should give no error while running print(1) since child has print(int i ) funciton, but it gives an error that parent class does not have print(int i) funciton.
Now for another scenario i add print(int i) function in the parent as well then everything works as expected parent class's function is overridden by child.
Also if i just add a print(int i) funciton in the parent only and remove it from the child then also this code works and it prints that parent function , that is also an expected behaviour.
this is the only case which seems to be giving an error , if someone could share some insight into this, that would be very helpful , thanks :).