Parent p=new Child() ?
- By using parent reference, we can call only methods available in parent class and we can't call child specific methods.
- we can use parent reference to hold any child class object.
class Parent {
int duplicateVariable = 10;
String parentString = "parent string value";
Parent() {
System.out.println("parent Constructor");
}
public void duplicate_method() {
System.out.println("duplicate method in Parent class");
}
public void parentMethod() {
System.out.println("Parent method");
}
}
class Child extends Parent {
int duplicateVariable = 20;
String childString = "child string value";
Child() {
System.out.println("child Constructor");
}
public void duplicate_method() {
System.out.println("duplicate method in child class");
}
public void childMethod() {
System.out.println("child method");
}
}
public class ParentChildProgram {
public static void main(String[] args) {
Parent parentObj = new Child();
System.out.println("Value=" + parentObj.duplicateVariable);// variable in parent class invoked
parentObj.duplicate_method();// duplicate method in child class is invoked
parentObj.parentMethod();
System.out.println(parentObj.parentString);
}
}
Output:
|
Parent p=new Child() |
- If we use parent reference to call specific child class specific methods we will get compile time error like below:
|
Parent P = new Child() compile time error |
Child c=new Child() ?- By using child reference we can call both parent and class methods.
- We can use child reference to hold only for that particular child class object only.
class Parent {
int duplicateVariable = 10;
String parentString = "parent string value";
Parent() {
System.out.println("parent Constructor");
}
public void duplicate_method() {
System.out.println("duplicate method in Parent class");
}
public void parentMethod() {
System.out.println("Parent method");
}
}
class Child extends Parent {
int duplicateVariable = 20;
String childString = "child string value";
Child() {
System.out.println("child Constructor");
}
public void duplicate_method() {
System.out.println("duplicate method in child class");
}
public void childMethod() {
System.out.println("child method");
}
}
public class ParentChildProgram {
public static void main(String[] args) {
Child childObj = new Child();
System.out.println("Value=" + childObj.duplicateVariable);// variable in child class invoked
childObj.duplicate_method();// duplicate method in child class is invoked
childObj.parentMethod();
childObj.childMethod();
System.out.println(childObj.parentString);
System.out.println(childObj.childString);
}
}
Output:
|
Child c=new Child() |
Please comment below to feedback or ask questions.
No comments:
Post a Comment
Please comment below to feedback or ask questions.