Upload
others
View
6
Download
1
Embed Size (px)
Citation preview
UNIT-II
Chapter-I
Inheritance:
Inheritance basics
Super keyword
Multi-level hierarchy
Abstract classes
final keyword with inheritance.
Herbert Schildt, “Java the Complete Reference,” Oracle Press, Ninth Edition, 2014.1
2
No. Object Class
1) Object is an instance of aclass.
Class is a blueprint ortemplate from which objects arecreated.
2) Object is a real worldentity such as pen, laptop,mobile, bed, keyboard,mouse, chair etc.
Class is a group of similar objects.
3) Object is a physical entity. Class is a logical entity.
4) Object is createdthrough newkeyword mainly
e.g.Student s1=new Student();
Class is declared using classkeyworde.g.class Student{}
Difference between object and class
3
No. Object Class
5) Object is created many
times as per requirement.
Class is declared once.
6) Object allocates memory
when it is created.
Class doesn't allocated memory
when it is created.
7) There are many ways to
create object in java such
as new keyword,
newInstance() method,
clone() method, factory
method and
deserialization.
There is only one way to define
class in java using class keyword.
Difference between object and class Cont..
More details
UNIT-II
Chapter-I
Inheritance:
Inheritance basics
Super keyword
Multi-level hierarchy
Abstract classes
final keyword with inheritance.
Herbert Schildt, “Java the Complete Reference,” Oracle Press, Ninth Edition, 2014.5
6
• Inheritance is one of the cornerstones of object-oriented
programming because it allows the creation of hierarchical
classifications.
• In the terminology of Java, a class that is inherited is called a
superclass.
• The class that does the inheriting is called a subclass.
• Therefore, a subclass is a specialized version of a superclass.
It inherits all of the members defined by the superclass and
adds its own, unique elements.
7
Cont..
• The idea behind inheritance in java is that you can create new
classes that are built upon existing classes.
• When you inherit from an existing class, you can reuse
methods and fields of parent class, and you can add new
methods and fields also.
• Inheritance represents the IS-A relationship, also known
as parent-child relationship.
Note: Unless specified otherwise, all classes are derived from a
single root class, named Object. If no parent class is explicitly
provided, the class Object is implicitly assumed.
Why use inheritance in java:
For Method Overriding (so runtime polymorphism can be
achieved).
For Code Reusability.
8
Cont..
class Subclass-name extends Superclass-name
{
//methods and fields
}
• The extends keyword indicates that you are making a new
class that derives from an existing class.
• In the terminology of Java, a class that is inherited is called a
super class. The new class is called a subclass.
9
Cont..// 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)); } }
10
Cont..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(); } }
11
Cont..
Output:
Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9
Sum of i, j and k in subOb:
i+j+k: 24
12
Cont..
Member Access and Inheritance
class A {
int i; // public by default
private int j; // private to A
…….
}
Note: A class member that has been declared as private will
remain private to its class. It is not accessible by any code
outside its class, including subclasses.
UNIT-II
Chapter-I
Inheritance:
Inheritance basics
Super keyword
Multi-level hierarchy
Abstract classes
final keyword with inheritance.
Herbert Schildt, “Java the Complete Reference,” Oracle Press, Ninth Edition, 2014.13
14
Member Access Rules:
• A subclass includes all of the members of its super class, I
cannot access those members of the super class that have been
declared as private.
• A class member that has been declared as private will remain
private to its class. It is not accessible by any code outside its
class, including subclasses.
super keyword in java
• The super keyword in java is a reference variable which is used
to refer immediate parent class object.
• Whenever you create the instance of subclass, an instance of
parent class is created implicitly which is referred by super
reference variable.
15
Cont..
Usage of super Keyword
1. super can be used to refer immediate parent class instance
variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class
constructor.
16
1.super is used to refer immediate parent class instance variable.
class Animal{
String color="white"; }
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
} }
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
Cont..
Output:Blackwhite
17
2) super can be used to invoke parent class method
• It should be used if subclass contains the same method as
parent class. In other words, it is used if method is overridden.
class Animal{
void eat(){System.out.println("eating...");} }
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){ super.eat(); bark(); } }
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work(); }}
Output:eating...barking...
Cont..
18
3) super is used to invoke parent class constructor.
class Animal{
Animal()
{
System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
} }
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog(); }}
Output:
animal is created
dog is created
Cont..
19
Types of inheritance in javaCont..
20
Cont..
Note: Multiple inheritance is not supported in java through class.
UNIT-II
Chapter-I
Inheritance:
Inheritance basics
Super keyword
Multi-level hierarchy
Abstract classes
final keyword with inheritance.
Herbert Schildt, “Java the Complete Reference,” Oracle Press, Ninth Edition, 2014.21
22
Creating multilevel hierarchy
• Multilevel inheritance, it is a concept of grandparent class. If
we take the example of above diagram then class C inherits
class B and class B inherits class A which means B is a parent
class of C and A is a parent class of B.
• So in this case class C is implicitly inheriting the properties
and method of class A along with B that’s what is called
multilevel inheritance.
23
class Animal{void eat(){System.out.println("eating...");}
}class Dog extends Animal{
void bark(){System.out.println("barking...");}}class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}}class TestInheritance2{public static void main(String args[]){
BabyDog d=new BabyDog();d.weep();d.bark();d.eat();
}}Output:weeping...barking...eating...
Cont..
24
class Animal{void eat(){System.out.println("eating...");}
}class Dog extends Animal{
void bark(){System.out.println("barking...");}}class Cat extends Animal{
void meow(){System.out.println("meowing...");}}class TestInheritance3{public static void main(String args[]){
Cat c=new Cat();c.meow();c.eat();//c.bark();//C.T.Error
}}Output:meowing...eating…
Cont..Hierarchical
25
Why multiple inheritance is not supported in java?
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B {//suppose if it were
public static void main(String args[]){
C obj=new C();
obj.msg();//Now which msg() method would be invoked?
} }
Compile Time Error
Cont..
UNIT-II
Chapter-I
Inheritance:
Inheritance basics
Super keyword
Multi-level hierarchy
Abstract classes
final keyword with inheritance.
Herbert Schildt, “Java the Complete Reference,” Oracle Press, Ninth Edition, 2014.26
27
No. Method Overloading Method Overriding
1) Method overloading is used to
increase the readability of the
program.
Method overriding is used to provide the
specific implementation of the method that is
already provided by its super class.
2) Method overloading is
performed within class.
Method overriding occurs in two classes that
have IS-A (inheritance) relationship.
3) In case of method
overloading, parameter must
be different.
In case of method overriding, parameter
must be same.
4) Method overloading is the
example of compile time
polymorphism.
Method overriding is the example of run time
polymorphism.
5) In java, method overloading
can't be performed by
changing return type of the
method only. Return type can
be same or different in method
overloading. But you must
have to change the parameter.
Return type must be same or covariant in
method overriding.
Difference between method overloading and method overriding
28
Cont..
29
class Bank{int getRateOfInterest(){return 0;}
}class SBI extends Bank{
int getRateOfInterest(){return 8;}}class ICICI extends Bank{
int getRateOfInterest(){return 7;}}class AXIS extends Bank{
int getRateOfInterest(){return 9;}}class Test2{public static void main(String args[]){
SBI s=new SBI();ICICI i=new ICICI();AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
} }
Test it NowOutput:SBI Rate of Interest: 8ICICI Rate of Interest: 7AXIS Rate of Interest: 9
Cont..
30
• There are situations in which you will want to define a
superclass that declares the structure of a given abstraction
without providing a complete implementation of every
method.
• Abstraction is a process of hiding the implementation details
and showing only functionality to the user.
• A class that is declared with abstract keyword, is known as
abstract class in java. It can have abstract and non-abstract
methods (method with body).
• Another way, it shows only important things to the user and
hides the internal details for example sending sms, you just
type the text and send the message. You don't know the
internal processing about the message delivery.
Cont..
31
Note: Abstraction lets you focus on what the object does instead
of how it does it.
Ways to achieve Abstraction
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)
Abstract class
• A class that is declared as abstract is known as abstract class.
It needs to be extended and its method implemented. It
cannot be instantiated.
• Example:
abstract class A{}
abstract methodA method that is declared as abstract and does not haveimplementation is known as abstract method.
Cont..
32
// A Simple demonstration of abstract.
abstract class A {
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo() {
System.out.println("This is a concrete method.");
} }
class B extends A {
void callme() {
System.out.println("B's implementation of callme.");
} }
class AbstractDemo {
public static void main(String args[]) {
B b = new B();
b.callme();
b.callmetoo();
} }
Cont..
33
Note:
1. An abstract class can have data member, abstract method,
method body, constructor and even main() method.
2. If there is any abstract method in a class, that class must be
abstract.
3. If you are extending any abstract class that have abstract
method, you must either provide the implementation of the
method or make this class abstract.
Cont..
34
Scenario: 1
Shape is the abstract class, its implementation is provided by
the Rectangle and Circle classes. Mostly, we don't know about
the implementation class (i.e. hidden to the end user) and
object of the implementation class is provided by the factory
method. draw()
Scenario: 2
Bank is the abstract class, its implementation is provided by
the ICICI and SBI classes. Return of interest
Cont..
35
abstract class Shape{abstract void draw();}//In real scenario, implementation is provided by others i.e. unknown by end userclass Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}}
class Circle1 extends Shape{void draw(){System.out.println("drawing circle");}}
//In real scenario, method is called by programmer or userclass TestAbstraction1{public static void main(String args[]){
Shape s=new Circle1();//In real scenario, object is provided through method e.g. getShape() method
s.draw();}}
Cont..
36
abstract class Bank{abstract int getRateOfInterest();}class SBI extends Bank{
int getRateOfInterest(){return 7;}}class PNB extends Bank{
int getRateOfInterest(){return 8;}}
class TestBank{public static void main(String args[]){
Bank b;b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}}
Cont..
UNIT-II
Chapter-I
Inheritance:
Inheritance basics
Super keyword
Multi-level hierarchy
Abstract classes
final keyword with inheritance.
Herbert Schildt, “Java the Complete Reference,” Oracle Press, Ninth Edition, 2014.37
38
Final Keyword in Java
The final keyword in java is used to restrict the user. The java
final keyword can be used in many context. Final can be:
1. variable
2. method
3. class
39
Example of final variable
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
} }//end of class
Output: Compile Time Error
Cont..
40
Example of final method
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph"
);}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
} }
Test it Now
Output: Compile Time Error
Note: Using final keyword, prevent Method Overriding.
Cont..
41
Example of final classfinal class Bike{}
class Honda1 extends Bike{void run()
{System.out.println("running safely with 100kmph");
}public static void main(String args[]){Honda1 honda= new Honda();honda.run();} }
Test it NowOutput: Compile Time Error
Uses:• If you make any variable as final, you cannot change the
value of final variable (It will be constant).• If you make any method as final, you cannot override it.• If you make any class as final, you cannot extend it.
Cont..
42
Is final method inherited?
Ans.) Yes, final method is inherited but you cannot override it.
For Example:
class Bike{
final void run(){
System.out.println("running...");}
}
class Honda2 extends Bike{
public static void main(String args[]){
new Honda2().run();
} }
Test it Now
Output: running...
Cont..