SlideShare a Scribd company logo
1 of 38
Inheritance
Chapter 8
• 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.
Hierarchy Of Classes
Employee
Associate Trainer ProjectManager
is an
Generalised
Class
Specialised Classes
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
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)
• 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");
• Employee e2 = new Employee();
• e2.name ="EmployeeHellen";
• e2.age = 25;
• e2.eat("Office Food");
• e2.work("Development work");
• Student st = new Student();
• st.name ="StudentHari";
• st.age =15;
• st.eat("Canteen Food");
• st.learn("History");
• } }
//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();}}
// 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);
}
}
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.
• 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;
• }
• }
• //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;
• }
• }
• 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();
• }
• }
• 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();
• }
• }
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();
}
}
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();
}
}
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
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
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
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
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();} }
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.
Method Overriding and Polymorphism
Employee
void displayRole() {
System.out.println(“I’m with Cognizant”);
}
Associate
void displayRole() {
System.out.println(
“I develop Programs”
);
}
Trainer
void displayRole() {
System.out.println(
“I Train Associates”
);
}
ProjectManager
void displayRole() {
System.out.println(
“I manage Projects”
);
}
Employee e = new Employee();
e.displayRole();
Method Overriding and Polymorphism
Employee
void displayRole() {
System.out.println(“I’m with Cognizant”);
}
Associate
void displayRole() {
System.out.println(
“I develop Programs”
);
}
Trainer
void displayRole() {
System.out.println(
“I Train Associates”
);
}
ProjectManager
void displayRole() {
System.out.println(
“I manage Projects”
);
}
Employee e = new Associate();
e.displayRole();
Method Overriding and Polymorphism
Employee
void displayRole() {
System.out.println(“I’m with Cognizant”);
}
Associate
void displayRole() {
System.out.println(
“I develop Programs”
);
}
Trainer
void displayRole() {
System.out.println(
“I Train Associates”
);
}
ProjectManager
void displayRole() {
System.out.println(
“I manage Projects”
);
}
Employee e = new Trainer();
e.displayRole();
Method Overriding and Polymorphism
Employee
void displayRole() {
System.out.println(“I’m with Cognizant”);
}
Associate
void displayRole() {
System.out.println(
“I develop Programs”
);
}
Trainer
void displayRole() {
System.out.println(
“I Train Associates”
);
}
ProjectManager
void displayRole() {
System.out.println(
“I manage Projects”
);
}
Employee e = new ProjectManager();
e.displayRole();
• 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
• }
• }
• //
• 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);
• }
• }
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!");
• }
• }
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() {
}
• 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);
• }
• }
• 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());
• }
• }
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) {
}
• 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.
• 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
• 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");
• }
• }
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");
• }
• }
• 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();
• }}

More Related Content

What's hot

Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017Alena Holligan
 
The Ring programming language version 1.8 book - Part 80 of 202
The Ring programming language version 1.8 book - Part 80 of 202The Ring programming language version 1.8 book - Part 80 of 202
The Ring programming language version 1.8 book - Part 80 of 202Mahmoud Samir Fayed
 
The Ring programming language version 1.5.4 book - Part 73 of 185
The Ring programming language version 1.5.4 book - Part 73 of 185The Ring programming language version 1.5.4 book - Part 73 of 185
The Ring programming language version 1.5.4 book - Part 73 of 185Mahmoud Samir Fayed
 
The Ring programming language version 1.5.1 book - Part 29 of 180
The Ring programming language version 1.5.1 book - Part 29 of 180The Ring programming language version 1.5.1 book - Part 29 of 180
The Ring programming language version 1.5.1 book - Part 29 of 180Mahmoud Samir Fayed
 

What's hot (8)

Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017
 
Best Guide for Javascript Objects
Best Guide for Javascript ObjectsBest Guide for Javascript Objects
Best Guide for Javascript Objects
 
Object calisthenics
Object calisthenicsObject calisthenics
Object calisthenics
 
The Ring programming language version 1.8 book - Part 80 of 202
The Ring programming language version 1.8 book - Part 80 of 202The Ring programming language version 1.8 book - Part 80 of 202
The Ring programming language version 1.8 book - Part 80 of 202
 
The Ring programming language version 1.5.4 book - Part 73 of 185
The Ring programming language version 1.5.4 book - Part 73 of 185The Ring programming language version 1.5.4 book - Part 73 of 185
The Ring programming language version 1.5.4 book - Part 73 of 185
 
Constructors
ConstructorsConstructors
Constructors
 
Clojure Deep Dive
Clojure Deep DiveClojure Deep Dive
Clojure Deep Dive
 
The Ring programming language version 1.5.1 book - Part 29 of 180
The Ring programming language version 1.5.1 book - Part 29 of 180The Ring programming language version 1.5.1 book - Part 29 of 180
The Ring programming language version 1.5.1 book - Part 29 of 180
 

Similar to Inheritance in Java

Similar to Inheritance in Java (20)

6.INHERITANCE.ppt(MB).ppt .
6.INHERITANCE.ppt(MB).ppt                    .6.INHERITANCE.ppt(MB).ppt                    .
6.INHERITANCE.ppt(MB).ppt .
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Super keyword.23
Super keyword.23Super keyword.23
Super keyword.23
 
Classes, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaClasses, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with Java
 
Mpl 9 oop
Mpl 9 oopMpl 9 oop
Mpl 9 oop
 
UNIT_-II_2021R.pptx
UNIT_-II_2021R.pptxUNIT_-II_2021R.pptx
UNIT_-II_2021R.pptx
 
Chapter 04 inheritance
Chapter 04 inheritanceChapter 04 inheritance
Chapter 04 inheritance
 
Constructor
ConstructorConstructor
Constructor
 
unit 2 java.pptx
unit 2 java.pptxunit 2 java.pptx
unit 2 java.pptx
 
Class introduction in java
Class introduction in javaClass introduction in java
Class introduction in java
 
C#2
C#2C#2
C#2
 
Inheritance.ppt
Inheritance.pptInheritance.ppt
Inheritance.ppt
 
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdfJava-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
 
Inheritance
InheritanceInheritance
Inheritance
 
Oops
OopsOops
Oops
 
5.CLASSES.ppt(MB)2022.ppt .
5.CLASSES.ppt(MB)2022.ppt                       .5.CLASSES.ppt(MB)2022.ppt                       .
5.CLASSES.ppt(MB)2022.ppt .
 
Object Oriented Programming using C++ - Part 2
Object Oriented Programming using C++ - Part 2Object Oriented Programming using C++ - Part 2
Object Oriented Programming using C++ - Part 2
 
Lecture4
Lecture4Lecture4
Lecture4
 
Inheritance in C++.ppt
Inheritance in C++.pptInheritance in C++.ppt
Inheritance in C++.ppt
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 

More from Krishna Sujeer

1-informatica-training
1-informatica-training1-informatica-training
1-informatica-trainingKrishna Sujeer
 
SAP REQRUITMENT NOTES03
SAP REQRUITMENT NOTES03SAP REQRUITMENT NOTES03
SAP REQRUITMENT NOTES03Krishna Sujeer
 
KRISHNA NAYAKSujeer B.E(IT), MS(QM) , PGDCA,ITIL PMP,
KRISHNA NAYAKSujeer B.E(IT), MS(QM) , PGDCA,ITIL PMP,KRISHNA NAYAKSujeer B.E(IT), MS(QM) , PGDCA,ITIL PMP,
KRISHNA NAYAKSujeer B.E(IT), MS(QM) , PGDCA,ITIL PMP,Krishna Sujeer
 
KRISHNA NAYAKSujeer B.E(IT), MS(QM) , PGDCA,ITIL PMP,
KRISHNA NAYAKSujeer B.E(IT), MS(QM) , PGDCA,ITIL PMP,KRISHNA NAYAKSujeer B.E(IT), MS(QM) , PGDCA,ITIL PMP,
KRISHNA NAYAKSujeer B.E(IT), MS(QM) , PGDCA,ITIL PMP,Krishna Sujeer
 
KEYTAKEAWAYAS Krishna Nayak v2.0 Notes
KEYTAKEAWAYAS Krishna Nayak v2.0 NotesKEYTAKEAWAYAS Krishna Nayak v2.0 Notes
KEYTAKEAWAYAS Krishna Nayak v2.0 NotesKrishna Sujeer
 
Recruitment_Process[1]
Recruitment_Process[1]Recruitment_Process[1]
Recruitment_Process[1]Krishna Sujeer
 
ETI_Krishna_Nayak_Sujeer
ETI_Krishna_Nayak_SujeerETI_Krishna_Nayak_Sujeer
ETI_Krishna_Nayak_SujeerKrishna Sujeer
 
itil2011foundation-allvolumes-signed-131020235516-phpapp01 (1)
itil2011foundation-allvolumes-signed-131020235516-phpapp01 (1)itil2011foundation-allvolumes-signed-131020235516-phpapp01 (1)
itil2011foundation-allvolumes-signed-131020235516-phpapp01 (1)Krishna Sujeer
 
Software testing strategies
Software testing strategiesSoftware testing strategies
Software testing strategiesKrishna Sujeer
 
Software Quality Management
Software Quality ManagementSoftware Quality Management
Software Quality ManagementKrishna Sujeer
 
Basic adminstration and configuration techniques
Basic adminstration and configuration techniquesBasic adminstration and configuration techniques
Basic adminstration and configuration techniquesKrishna Sujeer
 
LSI - PMP - Training material
LSI - PMP - Training materialLSI - PMP - Training material
LSI - PMP - Training materialKrishna Sujeer
 
SAP HCM CORE MODULES V1.0
SAP HCM CORE MODULES V1.0SAP HCM CORE MODULES V1.0
SAP HCM CORE MODULES V1.0Krishna Sujeer
 
MASTER_Trainer Notes_V5.2
MASTER_Trainer Notes_V5.2MASTER_Trainer Notes_V5.2
MASTER_Trainer Notes_V5.2Krishna Sujeer
 

More from Krishna Sujeer (20)

1-informatica-training
1-informatica-training1-informatica-training
1-informatica-training
 
SAP REQRUITMENT NOTES03
SAP REQRUITMENT NOTES03SAP REQRUITMENT NOTES03
SAP REQRUITMENT NOTES03
 
KRISHNA NAYAKSujeer B.E(IT), MS(QM) , PGDCA,ITIL PMP,
KRISHNA NAYAKSujeer B.E(IT), MS(QM) , PGDCA,ITIL PMP,KRISHNA NAYAKSujeer B.E(IT), MS(QM) , PGDCA,ITIL PMP,
KRISHNA NAYAKSujeer B.E(IT), MS(QM) , PGDCA,ITIL PMP,
 
KRISHNA NAYAKSujeer B.E(IT), MS(QM) , PGDCA,ITIL PMP,
KRISHNA NAYAKSujeer B.E(IT), MS(QM) , PGDCA,ITIL PMP,KRISHNA NAYAKSujeer B.E(IT), MS(QM) , PGDCA,ITIL PMP,
KRISHNA NAYAKSujeer B.E(IT), MS(QM) , PGDCA,ITIL PMP,
 
KEYTAKEAWAYAS Krishna Nayak v2.0 Notes
KEYTAKEAWAYAS Krishna Nayak v2.0 NotesKEYTAKEAWAYAS Krishna Nayak v2.0 Notes
KEYTAKEAWAYAS Krishna Nayak v2.0 Notes
 
Selenium.PDF
Selenium.PDFSelenium.PDF
Selenium.PDF
 
Recruitment_Process[1]
Recruitment_Process[1]Recruitment_Process[1]
Recruitment_Process[1]
 
ETI_Krishna_Nayak_Sujeer
ETI_Krishna_Nayak_SujeerETI_Krishna_Nayak_Sujeer
ETI_Krishna_Nayak_Sujeer
 
KRISHNA_NAYAK_Sujeer
KRISHNA_NAYAK_SujeerKRISHNA_NAYAK_Sujeer
KRISHNA_NAYAK_Sujeer
 
itil2011foundation-allvolumes-signed-131020235516-phpapp01 (1)
itil2011foundation-allvolumes-signed-131020235516-phpapp01 (1)itil2011foundation-allvolumes-signed-131020235516-phpapp01 (1)
itil2011foundation-allvolumes-signed-131020235516-phpapp01 (1)
 
Software testing strategies
Software testing strategiesSoftware testing strategies
Software testing strategies
 
Software Processes
Software ProcessesSoftware Processes
Software Processes
 
Software Quality Management
Software Quality ManagementSoftware Quality Management
Software Quality Management
 
Software Testing
Software TestingSoftware Testing
Software Testing
 
Basic adminstration and configuration techniques
Basic adminstration and configuration techniquesBasic adminstration and configuration techniques
Basic adminstration and configuration techniques
 
LSI - PMP - Training material
LSI - PMP - Training materialLSI - PMP - Training material
LSI - PMP - Training material
 
SAP HCM CORE MODULES V1.0
SAP HCM CORE MODULES V1.0SAP HCM CORE MODULES V1.0
SAP HCM CORE MODULES V1.0
 
20410B_01
20410B_0120410B_01
20410B_01
 
MASTER_Trainer Notes_V5.2
MASTER_Trainer Notes_V5.2MASTER_Trainer Notes_V5.2
MASTER_Trainer Notes_V5.2
 
1- java
1- java1- java
1- java
 

Inheritance in Java

  • 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.
  • 3. Hierarchy Of Classes Employee Associate Trainer ProjectManager is an Generalised Class Specialised Classes
  • 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");
  • 7. • Employee e2 = new Employee(); • e2.name ="EmployeeHellen"; • e2.age = 25; • e2.eat("Office Food"); • e2.work("Development work"); • Student st = new Student(); • st.name ="StudentHari"; • st.age =15; • st.eat("Canteen Food"); • st.learn("History"); • } }
  • 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.
  • 23. Method Overriding and Polymorphism Employee void displayRole() { System.out.println(“I’m with Cognizant”); } Associate void displayRole() { System.out.println( “I develop Programs” ); } Trainer void displayRole() { System.out.println( “I Train Associates” ); } ProjectManager void displayRole() { System.out.println( “I manage Projects” ); } Employee e = new Employee(); e.displayRole();
  • 24. Method Overriding and Polymorphism Employee void displayRole() { System.out.println(“I’m with Cognizant”); } Associate void displayRole() { System.out.println( “I develop Programs” ); } Trainer void displayRole() { System.out.println( “I Train Associates” ); } ProjectManager void displayRole() { System.out.println( “I manage Projects” ); } Employee e = new Associate(); e.displayRole();
  • 25. Method Overriding and Polymorphism Employee void displayRole() { System.out.println(“I’m with Cognizant”); } Associate void displayRole() { System.out.println( “I develop Programs” ); } Trainer void displayRole() { System.out.println( “I Train Associates” ); } ProjectManager void displayRole() { System.out.println( “I manage Projects” ); } Employee e = new Trainer(); e.displayRole();
  • 26. Method Overriding and Polymorphism Employee void displayRole() { System.out.println(“I’m with Cognizant”); } Associate void displayRole() { System.out.println( “I develop Programs” ); } Trainer void displayRole() { System.out.println( “I Train Associates” ); } ProjectManager void displayRole() { System.out.println( “I manage Projects” ); } Employee e = new ProjectManager(); e.displayRole();
  • 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(); • }}