Inheritance
If there are multiple entities with some common fields/states as well as some specific fields/states, then we can define a common class for both of them and specific classes can be extended from the common class. Specfic fields/states can be added to the specific classes.
e.g If we take the example of a bank then we can have two entities Employee and Customer, and both are person. So both entities inherit the attributes of a person.
Lets have a look at the below class Person that represents a person:
package oops.inheritance; public class Person { String name; String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
Employee class extending Person class :
package oops.inheritance; public class Employee extends Person { int employeeId; String department; public int getEmployeeId() { return employeeId; } public void setEmployeeId(int employeeId) { this.employeeId = employeeId; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } }Here Employee class is inheriting the name and address fields from Person class.
And on top of name/address property adding it's own fields employeeId and department.
Customer class extending Person class :
package oops.inheritance; public class Customer extends Person { String customerId; long accountNumber; public String getCustomerId() { return customerId; } public void setCustomerId(String customerId) { this.customerId = customerId; } public long getAccountNumber() { return accountNumber; } public void setAccountNumber(long accountNumber) { this.accountNumber = accountNumber; } }Here Customer class is inheriting the name and address fields from Person class.
And on top of name/address property adding it's own fields customerId and accountNumber.
Important Rules of Inheritance
- A parent can hold reference to its child class objects and invoke only those methods of child whose are inherited/overridden from parent class. Because at compile time, parent class knows only those methods which are defined as part of itself, and overridden methods are identified at run time.
- So even if you try to call a method that is not inherited/overridden from parent class, it will fail at compile time.