Parent p = new Child();
ORParent p = new Parent();
Child c = new Child();
p = c; // Subclass to Super Class, it is valid
Parent p = new Child(); // implicit casting
Child c = c = (Child) p; // explicit casting
package com.javaiq.example.java;
public class Person {
public void getPersonName() {
System.out.println("getPersonName() :: In Parent Class :: I am a persion. ");
}
public void getParentName() {
System.out.println("In Parent Class :: i am only in parent class not override in child class.");
}
}
package com.javaiq.example.java;
public class Employee extends Person {
@Override
public void getPersonName() {
System.out.println("getPersonName() :: In Employee Class :: I am a Employee.");
}
public void getEmployeeName() {
System.out.println("In Employee Class :: I am a Employee - non override method .");
}
}
package com.javaiq.example.java;
public class PersonMain {
public static void main(String[] args) {
System.out.println("#### Parent class Output ###");
/*
* We can access all method present in Person class, here Person is Super Class
*/
Person person = new Person();
person.getPersonName();
person.getParentName();
System.out.println("");
System.out.println("#### Child Output ###");
/*
* We can access all method present in Employee class and Person class, here
* Employee is Sub Class
*/
Employee employee = new Employee();
employee.getPersonName();
employee.getEmployeeName();
employee.getParentName();
System.out.println("");
System.out.println("#### Upcasting Output ###");
/*
* We can access only override in employee (Sub class) and all methods person (Super class)
* class methods
*/
Person personRef = new Employee();
personRef.getPersonName();
personRef.getPersonName();
System.out.println("");
System.out.println("#### Downcasting Output ###");
Employee employeeRef1 = (Employee) personRef;
employeeRef1.getPersonName(); // present in both class, and override in child class
employeeRef1.getEmployeeName(); // only present in child class
employeeRef1.getParentName(); // only present in parent class
}
}
#### Parent class Output ###
getPersonName() :: In Parent Class :: I am a persion.
In Parent Class :: i am only in parent class not override in child class.
#### Child Output ###
getPersonName() :: In Employee Class :: I am a Employee.
In Employee Class :: I am a Employee - non override method .
In Parent Class :: i am only in parent class not override in child class.
#### Upcasting Output ###
getPersonName() :: In Employee Class :: I am a Employee.
getPersonName() :: In Employee Class :: I am a Employee.
#### Downcasting Output ###
getPersonName() :: In Employee Class :: I am a Employee.
In Employee Class :: I am a Employee - non override method .
In Parent Class :: i am only in parent class not override in child class.
No comments:
Post a Comment