- Inheritance allows a subclass to inherit attributes and behaviors of its superclass. The subclass can add its own unique attributes and behaviors as well.
- When a subclass constructor calls the superclass constructor using super(), it must be the first statement in the subclass constructor. This initializes the superclass portion of the object before initializing the subclass.
- Method overriding occurs when a subclass defines a method with the same name, parameters, and return type as a method in its superclass. The subclass's version overrides or replaces the superclass version.
- The final keyword can be applied to classes to prevent subclasses from being created, and to methods to prevent overriding.
- The toString() method can be overridden in subclasses to return a custom string representation
2. • A class that is inherited is called a superclass.
• The class that does the inheriting is called a subclass.
• It inherits all of the instance variables and methods defined by the
superclass and adds its own, unique elements.
• cannot access those members of the superclass that have been declared as
private
• The idea behind inheritance is that you can create new classes (sub class
or derived class) that are built on existing classes (Base class or super
class).
• When you inherit from an existing class, you reuse (or inherit) its methods
and fields and you add new methods and fields to adapt your new class to
new situations. This technique is essential in Java programming.
4. Constructor and Inheritance
Inheritance is
not possible
without a
Constructor
public class Employee {
protected int employeeID;
protected String employeeName;
public Employee() {
System.out.println(“Employee Created”);
}
}
class Associate extends Employee {
protected int employeeID;
private int noOfProjects;
public Associate() {
System.out.println(“Associate Created”);
}
public static void main(String[] args) {
Associate a = new Associate();
}
}
This gets executed
first
Then this
On Creating
an Object for the
Sub Class
Inheritance is
Top-Down
approach
5. Extending a Class
public class Employee {
protected int employeeID;
protected String employeeName;
}
class Associate extends Employee {
private int noOfProjects;
}
Employee
employeeID
employeeName
Associate
employeeID
employeeName
noOfProjects
extends
protected allows the
access to members only to
the sub classes (derived classes)
6. • public class Employee extends Person{
• void work(String workType){
• System.out.println("Employee "+name+" does "+workType);
• }}
• public class Student extends Person {
• void learn(String subject){
• System.out.println("Student "+name+" does "+ subject);
• }}
• public class InheritenceDemo {
• public static void main(String[] args) {
• Employee e = new Employee();
• e.name ="EmployeeAllan";
• e.age = 25;
• e.eat("Office Food");
• e.work("Development work");
• Employee e1 = new Employee();
• e1.name ="EmployeeRobert";
• e1.age = 25;
• e1.eat("Office Food");
• e1.work("Development work");
8. //A simple example of inheritance. //Create a superclass.
class A { int i, j;
void showij() { System.out.println("i and j: " + i + " " + j);
} } //Create a subclass by extending class A.
class B extends A { int k;
void showk() { System.out.println("k: " + k); }
void sum() { System.out.println("i+j+k: " + (i+j+k)); } }
class SimpleInheritance {
public static void main(String args[]) {
A superOb = new A();
B subOb = new B(); //The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println(); /* The subclass has access to all public members of
its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: "); subOb.showij(); subOb.showk();
System.out.println();
• System.out.println("Sum of i, j and k in subOb:"); subOb.sum();
• //superOb.k = 13; //superOb.showk();//superOb.sum();}}
9. // A Superclass Variable Can Reference a Subclass Object
class RefDemo {
public static void main(String args[]) {
BoxWeight weightbox = new BoxWeight(3, 5, 7, 8.37);
Box plainbox = new Box();
double vol;
vol = weightbox.volume();
System.out.println("Volume of weightbox is " + vol);
System.out.println("Weight of weightbox is " +
weightbox.weight);
System.out.println();
// assign BoxWeight reference to Box reference
plainbox = weightbox; // weightbox = plainbox; Reverse means object casting
vol = plainbox.volume(); // OK, volume() defined in Box
System.out.println("Volume of plainbox is " + vol);
/* The following statement is invalid because plainbox
does not define a weight member. */
// System.out.println("Weight of plainbox is " + plainbox.weight);
}
}
10. super
• Class Box{
• double width;
• double height;
• double depth;
• }
• class BoxWeight extends Box {
• double weight; // weight of box
• // initialize width, height, and depth using super()
• BoxWeight(double w, double h, double d, double m) {
• super(w, h, d); // call superclass constructor
• weight = m;
• }
• }
• BoxWeight( ) calls super( ) with the parameters w, h, and d. This
causes the Box( ) constructor to be called, which initializes width,
height, and depth using these values. BoxWeight no longer
initializes these values itself. It only needs to initialize the value
unique to it: weight.
11. • class Box {
• private double width;
• private double height;
• private double depth;
• // construct clone of an object
• Box(Box ob) { // pass object to constructor
• width = ob.width;
• height = ob.height;
• depth = ob.depth;
• }// constructor used when all dimensions specified
• Box(double w, double h, double d) {
• width = w;
• height = h;
• depth = d;
• }
• // constructor used when no dimensions specified
• Box() {
• width = -1; // use -1 to indicate
• height = -1; // an uninitialized
• depth = -1; // box
• }
• // constructor used when cube is created
• Box(double len) {
• width = height = depth = len;
• }
• // compute and return volume
• double volume() {
• return width * height * depth;
• }
• }
12. • //BoxWeight now fully implements all constructors.
• class BoxWeight extends Box {
• double weight; // weight of box
• // construct clone of an object
• BoxWeight(BoxWeight ob) { // pass object to constructor
• super(ob);
• weight = ob.weight;
• }
• // constructor when all parameters are specified
• BoxWeight(double w, double h, double d, double m) {
• super(w, h, d); // call superclass constructor
• weight = m;
• }// default constructor
• BoxWeight() {
• super();
• weight = -1;
• }
• // constructor used when cube is created
• BoxWeight(double len, double m) {
• super(len);
• weight = m;
• }
• }
13. • class DemoSuper {
• public static void main(String args[]) {
• BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
• BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
• BoxWeight mybox3 = new BoxWeight(); // default
• BoxWeight mycube = new BoxWeight(3, 2);
• BoxWeight myclone = new BoxWeight(mybox1);
• double vol;
• vol = mybox1.volume();
• System.out.println("Volume of mybox1 is " + vol);
• System.out.println("Weight of mybox1 is " + mybox1.weight);
• System.out.println();
• vol = mybox2.volume();
• System.out.println("Volume of mybox2 is " + vol);
• System.out.println("Weight of mybox2 is " + mybox2.weight);
• System.out.println();
• vol = mybox3.volume();
• System.out.println("Volume of mybox3 is " + vol);
• System.out.println("Weight of mybox3 is " + mybox3.weight);
• System.out.println();
• vol = myclone.volume();
• System.out.println("Volume of myclone is " + vol);
• System.out.println("Weight of myclone is " + myclone.weight);
• System.out.println();
• vol = mycube.volume();
• System.out.println("Volume of mycube is " + vol);
• System.out.println("Weight of mycube is " + mycube.weight);
• System.out.println();
• }
• }
14. • class A2 {
• int i;
• }
• //Create a subclass by extending class A.
• class B2 extends A2 {
• int i; // this i hides the i in A
• B2(int a, int b) {
• super.i = a; // i in A
• i = b; // i in B
• }
• void show() {
• System.out.println("i in superclass: " + super.i);
• System.out.println("i in subclass: " + i);
• }
• }
• class UseSuper {
• public static void main(String args[]) {
• B2 subOb = new B2(1, 2);
• subOb.show();
• }
• }
15. When Constructors Are Called // Multilevel Hierarchy
* super( ) must be the first statement executed in a subclass’ constructor,
// Create a super class.
class A {
A() {
System.out.println("Inside A's constructor.");
}
}
// Create a subclass by extending class A.
class B extends A {
B() {
System.out.println("Inside B's constructor.");
}
}
// Create another subclass by extending B.
class C extends B {
C() {
System.out.println("Inside C's constructor.");
}
}
class CallingCons {
public static void main(String args[]) {
C c = new C();
}
}
16. class Employee1 {
protected int employeeID = 1;
protected String employeeName = "a";
}
class Associate extends Employee1
{
protected int employeeID = 2;
private int noOfProjects = 3;
public void display() {
System.out.println(employeeID);
System.out.println(employeeName);
System.out.println(noOfProjects);
System.out.println(super.employeeID);
}
}
public class Employee {
public static void main(String args[]) {
Employee1 e1 = new Employee1();
Associate a = new Associate();
a.display();
}
}
17. No Multiple Inheritance Support
Employee
Associate Trainer ProjectManager
SportsPerson
• Java doesn’t support Multiple Inheritance
• Instead it uses interfaces to implement multiple
behaviours to a class
• A class in Java cannot have more than one super
class
18. The Object Hierarchy
Employee
Associate Trainer Project Manager
java.lang.Object
extends by default
All java classes in java API
and all user defined
classes inherits methods
from Object class
Few methods that you can override in your class are:
public boolean equals(Object); // Checks the equality of object content
public String toString(); // String representation of the object
public int hashCode(); // HashCode generated using content
public void finalize(); // GC calls this before destroying object
Everything
is Object
in Javafinal java.lang.String
19. Information Hiding
public class Employee {
protected int employeeID;
protected String employeeName;
}
class Associate extends Employee {
protected int employeeID;
private int noOfProjects;
public void display() {
System.out.println(employeeID);
System.out.println(employeeName);
System.out.println(noOfProjects);
System.out.println(super.employeeID);
}
}
This hides employeeID
in Employee Class
Use
super keyword
to access hidden
super class
member
20. Calling Super Class Constructors
public class Employee {
protected int employeeID;
protected String employeeName;
public Employee() { }
public Employee(int employeeID,
String employeeName) {
this.employeeID = employeeID;
this.employeeName = employeeName;
}
}
class Associate extends Employee {
private int noOfProjects;
public Associate() { }
public Associate(int employeeID, String
employeeName, int noOfProjects) {
super(employeeID, employeeName);
this.noOfProjects = noOfProjects;
}
}
public static void main(String args[]) {
Associate a =
new Associate(123, “Jane”);
}
super() method can be
called only from a
constructor
super() method call should
be the first statement in a
Constructor
21. class Employee3 { protected int employeeID; protected String employeeName; public Employee3() { } public
Employee3(int employeeID,
String employeeName) {
this.employeeID = employeeID;
this.employeeName = employeeName;
}
void edisplay() {
System.out.println(employeeID);
System.out.println(employeeName);
}
}
class Associate1 extends Employee3 {
private int noOfProjects;
public Associate1() { }
public Associate1(int employeeID, String
employeeName, int noOfProjects) {
super(employeeID, employeeName);
this.noOfProjects = noOfProjects;
}
void display() {
System.out.println(employeeID);
System.out.println(employeeName);
System.out.println(noOfProjects);
// System.out.println(super.employeeID);
}
}
public class Employee2 {
public static void main(String args[]) {
Employee3 e = new Employee3(456, "Allan");
Associate1 a = new Associate1(123, "Jane", 1);
e.edisplay();
a.display();} }
22. Method overriding
When a method in a sub class has the same name and type signature as
method in its super class then the method in the sub class is said to be
override the method in the superclass.
Run-time polymorphism.
•
Overridden methods are another way that Java implements the “one
• interface, multiple methods” aspect of polymorphism.
27. • class A {
• int i, j;
• A(int a, int b) {
• i = a;
• j = b;
• }
• // display i and j
• void show() {
• System.out.println("i and j: " + i + " " + j);
• }
• }
• class B extends A {int k;
• B(int a, int b, int c) {
• super(a, b);
• k = c;
• }// display k – this overrides show() in A
• void show() {
• System.out.println("k: " + k);
• }}
• class Override {
• public static void main(String args[]) {
• B subOb = new B(1, 2, 3);
• subOb.show(); // this calls show() in B
• }
• }
28. • //
• class B extends A {
• int k;
• B(int a, int b, int c) {
• super(a, b);
• k = c;
• } void show() {
• super.show(); // this calls A's show()
• System.out.println("k: " + k);
• }
• }
29. Preventing Inheritance: Final Classes and Methods
• To prevent someone from forming a subclass from one of your
classes. Classes that cannot be extended are called final classes
• final class A {
• // ...
• }
• // The following class is illegal.
• class B extends A { // ERROR! Can't subclass A
• // ...
• }
• --------------------------------------------------------------------------------------------------------
• class A {
• final void meth() {
• System.out.println("This is a final method.");
• }
• }
• class B extends A {
• void meth() { // ERROR! Can't override.
• System.out.println("Illegal!");
• }
• }
30. Overriding toString()
Employee
private String empName;
public Employee() { }
public Employee(String n) {
empName = n;
}
public String getEmpName() {
return empName;
}
public String toString() {
}
Associate
public Associate() { }
public Associate(String n) {
super(n);
}
public void toString() {
return empName
+ “(Associate)”;
}
Object o = new Associate(“Jane”);
System.out.println(o);
//System.out.println(o.toString());
Object
public void toString() {
}
31. • class ToStringDemo {
• String name;
• int age;
• ToStringDemo(){
• name="abc";
• age=23;
• }
• public String toString() {
• return ("Name is " + name+ "nNum is " +
age);
• }
• public static void main(String arp[]) {
• ToStringDemo a=new ToStringDemo();
• System.out.println("Obj is " + a);
• }
• }
32. • class Employee {
• String empName;
• public Employee() { }
• public Employee(String n) {
• empName = n;
• }
• public String getEmpName() {
• return empName;
• }
• public String toString() {
• return empName;
• }
• }
• class Associate extends Employee{
• public Associate() { }
• public Associate(String n) {
• super(n);
• }
• public String toString() {
• return empName + "(Associate)";
• }
• }
• public class A{
• public static void main(String args[])
• {
• Object o = new Associate("Jane");
• System.out.println(o);
• System.out.println(o.toString());
• Employee e=new Employee("Balaji");
• System.out.println(e.getEmpName());
• }
• }
33. Overriding equals()
Employee
protected String empName;
public Employee() { }
public Employee(String n) {
empName = n;
}
public String getEmpName() {
return empName;
}
public boolean equals(Object o) {
}
Associate
public Associate() { }
public Associate(String n) {
super(n);
}
public boolean equals(Object o) {
Associate a = (Associate) o;
return empName
.equals(a.getEmpName());
}
Object o1 = new Associate(“Jane”);
Object o2 = new Associate(“Jane”);
if (o1.equals(o2))
System.out.println(“Equal”);
else
System.out.println(“Not Equal”);
Object
public boolean equals(Object o) {
}
34. • Object Casting:
• To use superclass objects where subclass objects are expected,
you must cast them explicitly.
• You won't lose any information in the cast, but you gain all the
methods and variables that the subclass defines.
• To cast an object to another class, you use the same operation as
for primitive types:
• (classname)object
• In this case, classname is the name of the destination class, and
object is a reference to the source object.
• Note that casting creates a reference to the old object of the type
classname; the old object continues to exist as it did before.
35. • The following example casts an instance of the class VicePresident
to an instance of the class Employee;
• VicePresident is a subclass of Employee with more information,
which here defines that the VicePresident has executive privileges:
• Employee emp = new Employee();
• VicePresident veep = new VicePresident();
• emp = veep;
• // no cast needed for upward use
• veep = (VicePresident)emp;
• // must cast explicitly
36. • class Employee{
• String empName;
• public Employee() { }
• public Employee(String n) {
• empName = n;
• }
• public String getEmpName() {
• return empName;
• }
• }
• class Associate extends Employee{
• public Associate() { }
• public Associate(String n) {
• super(n);
• }
• public boolean equals(Object o) {
• Associate a = (Associate) o;
• return empName.equals(a.getEmpName());
• }
• }
• public class C {
• public static void main(String args[]) {
• Object o1 = new Associate("Jane");
• Object o2 = new Associate("Jane1");
• if (o1.equals(o2))
• System.out.println("Equal");
• else
• System.out.println("Not Equal");
• }
• }
37. Function Returning Objects
• public class Animal {
• void eat(){
• System.out.println("Animal eats");
• }}
• public class Dog extends Animal {
• void eat(){
• System.out.println("Dog eats");
• }}
• public class Cat extends Animal {
• void eat(){
• System.out.println("Cat eats");
• }
• }
38. • public class Cage {
• static String code ="D";
• static Animal open(){
• if (code.equals("D")){
• Dog d = new Dog();
• return d;
• }
• if (code.equals("C")){
• Cat c = new Cat();
• return c;
• }
• return null;
• }
• public static void main(String[] args) {
• //Dog d = new Dog();
• //Cat c = new Cat();
• //d.eat();
• //c.eat();
• //Dog d1 = open();
• //d1.eat();
• code = args[0];
• Animal a = Cage.open();
• a.eat();
• }}