Beruflich Dokumente
Kultur Dokumente
1
Java
CONTENTS
1 Definition
2 Members which are not inherited
3 Super
4 What is happening ?
5 Order of initializations when subclass instance is created
6 protected access
7 Subclass outside the package
8 Conversion and casting
9 Overriding
10 Rules
2
Java
CONTENTS
3
Java
CONTENTS
4
Java
Know
• What inheritance is
• The use of the super keyword
• The implications of protected access specifier
• How conversion and casting work in case of
objects
5
Java
Know
. About Covariant returns
• What polymorphism is
• What happens if a private method, static method
or a member variable is re-declared.
• More about the final modifier
• What abstract classes are
6
Java
Be Able To
• Write Java programs using the power of
inheritance
7
Java
Definition
Teacher
Keyword to
denote
HOD inheritance
8
Java
Inheritance is an object oriented concept that allows
hierarchical classifications. Using this concept, a
general class can be created that defines traits common
to a set of related items. This class can then be inherited
by more specific classes with each adding those things
that are unique to it.
9
Java
package teacher;
public class HOD extends Teacher{
private String dateOfAppointment;
public HOD(String nm, String dt){
Calling super class
super(nm); constructor
dateOfAppointment=dt; }
public void viewGrade(Grade[] grades){
System.out.println(getName()+ " HOD viewing appraisal ");
for(Grade g:grades){ Calling super class method
System.out.println("Faculty :"+ g.getFaculty().getName());
10
Java
System.out.println("Student ID : "+
g.getStudent().getRegNo());
System.out.println("Grade: "+ g.getGrade());
}
}
public static void main(String str[]){
student.Student s1= new
student.Student("Ravi");
student.Student s2= new
student.Student(“Kumar");
HOD h=new HOD("Maverick","1.1.2006");
Teacher f= new Teacher("Sam"); 11
Java
Grade g[]=new Grade[2];
g[0]=new Grade(f,s1,"CS-001", Grade.A);
g[1]=new Grade(f,s2,"CS-001", Grade.B);
h.viewGrade(g); }
}
Folder 1
12
Java
Members which are not inherited
• Members which are not inherited:
-- Constructors
-- Private members
-- Default members (if classes are in the
different packages)
• Note however that public constructor can be
accessed by the subclass using super keyword.
13
Java
super
• Keyword super() is used to call the super class
constructor.
public HOD(String nm, String dt){
super(nm);//calls Teacher(String
name)
First statement in the constructor
}
• It can also be used to invoke super class methods from
the subclass method.
super.getFactId();
/* calls Teacher class’ getFactId()
method if invoked from a method of
HOD.*/
14
Java
public HOD(String nm, String dt){
//super(nm);
dateOfAppointment=dt;
}
…}
On compilation
15
Java
What is happening ?
public HOD(String nm, String dt){
Compiler inserts
super();
//super(nm); Attempting to call
dateOfAppointment=dt; }
..}
Teacher()
16
Java
Order of initializations when
subclass instance is created
1. Static initializations of super class take place:
Static variables are initialized and static blocks are
executed in the order of their appearance in the
code.
2. Static initializations of subclass class take place.
3. Instance initializations of super class: Instance
variables are initialized and instance blocks are
executed in the order of their appearance in the
code.
17
Java
4.Super class constructor is executed.
5.Instance initializations of subclass class.
6.Subclass class constructor is executed.
• Only after the super class object construction, sub
class construction happens.
• Let us look at an example and confirm this.
18
Java
class Order {
int i=0;
static {
System.out.println("Order class static block
");
}
Order(){
i=10;
System.out.println("Order class " + i);
}
} Folder 2
19
Java
class SubOrder extends Order{
int j;
static {
System.out.println("SubOrder class static
block");
}
SubOrder(){
j=15;
System.out.println("SubOrder class "+ j);
}
public static void main(String str[]){
new SubOrder();
}
} 20
Java
And this is the result of executing that code…
21
Java
protected access
22
Java
teacher admin
Teacher HOD
protected int factId;
accessible
Grade
23
Java
package teacher;
public class Teacher {
protected int factId;
private String name;
private static int id;
public int getFactId(){return factId;}
public String getName(){return name;}
public void setName(String name)
{ this.name=name;
Folder 3
} 24
Java
private int generateId(){
id++;
return id; }
public static int getId(){return id; }
public Teacher(String name){
this.name=name;
factId=generateId(); }
protected Teacher(){}
protected String retrieveName(int id){
/*code to retrieve name based on id*/
25
}} Java
package admin;
import teacher.*;
public class HOD extends Teacher{
private String dateOfAppointment;
public HOD(String nm, String dt){
super(nm); dateOfAppointment=dt; }
31
Java
Rules
The signature of the method( method name +
argument list) must exactly match.
The return type must be same or a subtype of
the return type of super class method (covariant
returns)
The access can be same or be increased.
(List of access specifiers in order of their
increasing accessibility:privatedefault
protectedpublic)
Instance methods can be overridden only if they
are inherited by the subclass.
Exception thrown cannot be new exceptions or
parent class exception.
We will deal with this later. 32
Java
Example 1
package teacher; package admin;
public class Teacher{ public class HOD extends
Teacher{
..
..
protected void
display(){ public void display(){
System.out.println( super.display();
"Name "+getName()); System.out.println(
System.out.println("ID "Date of appointment
:"+factId) ; "+dateOfAppointment);
Cannot have private
} }
or default access
} } specifier Folder 5
33
Java
Example 2
package admin;
package teacher;
public class HOD extends
public class Teacher{ Teacher{
.. ..
private void display(){ public void display(){
System.out.println(
System.out.println(
"Name "+getName());
"Name "+getFirstName()) System.out.println(
"Date of appointment
System.out.println("ID "+dateOfAppointment);
:"+factId) ; Can have any access
} specifier here. Since
}
} private methods are
Folder 6 not inherited !
} 34
Java
Covariant returns: Example 3
• In java 5.0, the overridden method’s return type can also
be a subtype of the original method return class’ subtype.
• For example:
public class Teacher{
public Teacher getInstance(){
return new Teacher();}
}
public class HOD extends Teacher{
public HOD getInstance(){
return new HOD();}} Folder 7
35
Java
Polymorphism
public static void print(Teacher
f[]){
for(int j=0;j<f.length;j++)
f[j].display(); Does this always call display()
} method of the Teacher class ?
public static void main(String
str[]){
Teacher f[]=new Teacher[2];
f[0]=new HOD(“Ned”,”1.1.2006”);
f[1]=new Teacher(“Sam”);
print(f);} Let us see…
Folder 8 36
Java
Polymorphism
37
Java
Polymorphism
HOD’s display()
Output:
Name :Ned
ID :1
Date of appointment 1.1.2006
39
Java
package teacher;
import admin.*;
public class Teacher{
…
public void display(){
System.out.println("Name :"+name) ;
System.out.println("ID :"+factId) ;
}
private void test(){
System.out.println("Faculty ");
display(); }
public static void main(String s[]){
Teacher f=new HOD("Ned","1.1.2006");
f.test();}} Folder 9
40
Java
package admin;
import teacher.*;
public class HOD extends Teacher{
…
public void display(){
super.display();
System.out.println("Date of
appointment: "+dateOfAppointment);}
public void test(){
System.out.println("HOD ");
display();
}
}
41
Java
Output is: Faculty Teacher’s test
Name :Ned
ID :1 HOD’s display()
Date of appointment: 1.1.2006
• Since the private methods are not inherited they are not
overridden.
• Since they are not overridden there is no polymorphic
behavior.
42
Java
Static member re-declaration
43
Java
Static member re-declaration
class ClassRoom{
static int capacity=50;
public static void printCapacity(){
System.out.println("Class Room seating
capacity "+ capacity); }}
45
Java
Hiding .Vs. Overriding
• So we come back to the same question- Are static
methods overridden?
• Answer is No!
• A method is said to be overridden only if it can
take the advantage of runtime polymorphism!.
• Otherwise it is only hidden.
• So the static methods of the super class are hidden
when they redefined in the sub class.
46
Java
Re-look at initializations
51
Java
package student;
public class Grade{
public final String getGrade(){
…
}}
52
Java
package student;
public final class Grade{
…
Compilation error
}}
package student;
public class MyGrade extends Grade{
…
}}
53
Java
Abstract class
• Declaring a class as an abstract class prevents
somebody from creating instances of that class.
• An abstract class can have abstract methods.
• Abstract methods are the methods that don’t have the
method body. They are just declarations.
• Any class that inherits from the abstract class must
override all the abstract methods and provide
implementations specific to that class.
• A class that does not override an abstract method must
be marked as an abstract class.
54
Java
Teacher
getName(), setName() Get the
common
getAddress(),setAddress methods into Person
… Person class <<abstract>>
getName()
getAddress()
Student
getName(), setName() Person class is a class created for
getAddress(),setAddress convenience so that we can enhance
reusability by inheritance. Instances of
… Person class have no meaning to our
application.
55
Java
Each person must have a unique id.
Teacher
Person getName()
<<abstract>> getAddress()
getName().. getUID()
getAddress().. …
abstract Implemented in
getUID() specific classes Student
getName()..
getAddress()..
getUID()
…
56
Java
package general;
public abstract class Person{
general.Person
teacher.Teacher student.Student
teacher.HOD 60
Java
Object
61
Java
Printing an object reference
import teacher.*;
public class Test{
The above code prints class name and the unique hashcode
of the object. Hashcode is an integer value that is
associated with an object. We shall see more about this
later when we do collections.
63
Java
Overriding toString()
package teacher;
public class Teacher{
…
public String toString(){
return getName()+" (" +factId+ ")";
}
}
Folder 15
64
Java
import teacher.*;
public class Test{
65
Java
Overriding toString()
• equals() method of Object class compares two
references using == operator.
• To compare the equality of two objects in terms of
its member variables we need to override the
equals method to suit our need.
66
Java
Overriding equals()
package student;
public class Grade{
public boolean equals(Object o){
Grade g=(Grade)o;
if (g.getGrade().equals(getGrade()))
return true;
else
return false;}
…} 67
Java
import student.*;
class Test{
public static void main(String str[]){
Grade g=new Grade(new Student("Raja"),new
int[]{ 80,85, 91,86, 82});