Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
17 views

OOP Through Java Unit - 3

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

OOP Through Java Unit - 3

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

UNIT III: Inheritance, types of inheritance, super keyword, final keyword, overriding and abstract

class. Interfaces, creating the packages, using packages, importance of CLASSPATH and java.lang
package. Exception handling, importance of try, catch, throw, throws and finally block, user defined
exceptions.

Inheritance:
The process by which one class acquires the properties i.e., variables, methods, constructors, sub
classes etc. from another class is called as inheritance (base class  derived class)
or
It is a process of creating a new class from the existing class is known as Inheritance.
Points to be remembered:
 Inheritance is the most important and useful feature of OOP.
 The existing class is known as parent class or base class or super class.
 The new class is known as child class or derived class or sub class.
 The Parent class is the class which provides features to another class.
 The Child class is the class which receives features from another class.
 It can be done by the extends keyword.
 It follows IS-A relationship.
Uses / Advantages:
 It allows us to reuse of code to improve the performance.
 For Method Overriding (to achieve runtime polymorphism).
 we can save time and effort.
 We can extend the class with our own properties.
 The derived class can also extend the properties of base class to generate more dominant
objects.
 The same base class is used for more derived classes.
 When a class is derived from more than one class, the derived classes have similar
properties to those of base classes.
Disadvantages:
 Complicated.
 Invoking methods creates overhead to the compiler.
Syntax:
class <ChildClassName> extends <ParentClassName>
{
//Implementation of child class
}

1
Example:

As displayed in the figure, Programmer is the


subclass and Employee is the superclass. The
relationship between the two classes
is Programmer IS-A Employee. It means that
Programmer is a type of Employee.

Types of Inheritance:
 There are 3 types of inheritances in Java
 Single inheritance
 Multi-level inheritance
 Hierarchical inheritance
Note:
Multiple inheritance and Hybrid inheritance can’t achieve directly but can achieve through
interface.
Single inheritance:
It is a process of creating / deriving a class from single base class is known as Single Inheritance.

 The class A serves as a base class for the derived class B

2
Example:
class A{ class SingleInheritance
int a=10; {
void show(){ public static void main(String a[])
System.out.print(a); {
} B b = new B();
} b.show();
class B extends A{ b.display();
int b=20; b.sum();
void display(){ }
System.out.print(b); }
} Output:
void sum(){ 10 20 30
System.out.print(a+b);
}
}

Multilevel inheritance:
It is a process of creating / deriving a class from already derived class is known as Multilevel
Inheritance.

 The class A serves as a base class for the derived class B, which in turn serves as a base
class for the derived class C.
 C class can directly access the variables and methods of A, B and C.

3
Example:
class A{ class MultiLevelInheritence{

int a=10; public static void main(String args[]){

void dispa(){ C obj = new C();

System.out.println(“A Class”); System.out.println(“C Class Variable=”+obj.c);

} obj.dispc();

class B extends A{ System.out.println(“B Class Variable=”+ obj.b);

int b=20; obj.dispb();

void dispb(){ System.out.println(“A Class Variable=”+ obj.a);

System.out.println(“B Class”); obj.dispa();

} }

class C extends B{ }

int c=30; Output:

void dispc(){ C Class Variable=30


C Class
System.out.println(“C Class”); B Class Variable=20
} B Class
A Class Variable=10
A Class

Hierarchical Inheritance:
It is a process of creating / deriving Multiple classes from single base class is known as
Hierarchical Inheritance.

 The class A serves as a base class for the derived class B, C and D.
 Using B Class Object, we can’t access C class properties and D class properties.
 Using C Class Object, we can’t access B class properties and D class properties.
 Using D Class Object, we can’t access B class properties and C class properties.

4
Example:
class A{ class HierarchicalInheritence{
int a=10; public static void main(String args[]){
void dispa(){ B obj1= new B();
System.out.println(“Parent”); C obj2 = new C();
} System.out.println(“B Class Variable=”+obj1.b);
class B extends A{ obj1.dispb();
int b=20; System.out.println(“A Class Variable=”+
void dispb(){ obj1.a); obj1.dispa();
System.out.println(“Child1”); System.out.println(“C Class Variable=”+obj2.c);
} obj2.dispc();
class C extends A{ System.out.println(“A Class Variable=”+
int c=30; obj2.a); obj2.dispa();
void dispc(){ }
System.out.println(“Child2”); }
} Output:
B Class Variable=20
Child1
A Class Variable=10
Parent
C Class Variable=30
Child2
A Class Variable=10
Parent

Hybrid Inheritance
 It is a combination of more than one type of inheritance
 If the combination consists of multiple inheritance not possible to implement

B C

× Invalid  Valid

5
Example:

class A class HybridInheritence {


{ public static void main(String args[]){
int a;
} C obj1= new C();

class B extends A D obj2= new D();


{ obj1.sum();
int b;
} obj2.mul();
class C extends A{ }
int c; }
C(){ Output:
a=10; c=20; Sum=30
} Mul=6000
void sum()
{
System.out.println (“Sum=”+(a+c));
}
}
class D extends B{
int d;
D()
{
a=10; b=20; d=30;
}
void mul()
{
System.out.println (“Mul=”+(a*b*d));
}
}

class Hybrid{
public static void main(String args[]){
C obj1= new C();
D obj2= new D();
obj1.sum();
obj2.mul();
}
}

6
Method Overriding:
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.
(or)
Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.
Imp Points:
 Method overriding is used for runtime polymorphism.
 Base class and Derived class should have the same method name (preference given to sub
class)
 Both the methods should have same return type, scope and signature (no., order of
parameters & Type of parameters)
 Private, Static and Final methods can’t be override.

Example:

class Parent{
void display()
{
System.out.println(“PARENT CLASS”);
}
}
class Child extends Parent{
void display()
{
System.out.println(“CHILD CLASS”);
}
}
class Override
{
public static void main(String args[])
{
Child c = new Child();
c.display();
}
}

Output:
CHILD CLASS

7
Method Overriding vs Method Overloading:
 Implementing the same thing with different ways i.e., Polymorphism

S. No Method Overloading Method Overriding

1 Can be achieved compile time Can be achieved run time polymorphism


polymorphism
2 Static binding / Early binding Dynamic binding / Late binding
3 Implemented within a single class Implemented in two different classes
4 No need of inheritance to achieve With the help of inheritance to achieve
this this
5 Used to increase readability of Used to provide different implementation
program of super class method
6 Method name should be same Method name should be same
7 Signature must be different Signature must be same
8 Return type can be same or different Return type should be same
9 Static methods can be overloaded Static methods can’t be overridden
10 Private methods can be overloaded Private methods can’t be overridden
11 Final methods can be overloaded Final methods can’t be overridden

Super Keyword:
 It can be used to access the variables, methods, constructors of base class into derived
class
 This will be used in derived class and the properties should be same in both the classes
 By using super.(property name), the derived class can access the properties of base class
 By default, constructor will be executed first

Example - 1:
class Parent
{
int a=40;
void display()
{
System.out.println(“PARENT CLASS”);
}
}

class Child extends Parent


{
int a=30;
8
void display()
{
System.out.println (“CHILD CLASS”);
System.out.println (a);
System.out.println(super.a);
super.display();
}
}
class SuperDemo
{
public static void main(String args[])
{
Child c = new Child();
c.display();
}
}

Output:
CHILD CLASS
30
40
PARENT CLASS

Example-2:
Super Keyword with Default Constructor:
class Parent{
Parent()
{
System.out.println("Parent class Constructor");
}
}
class Child extends Parent{
Child()
{
// invoke or call parent class constructor
super();
System.out.println(“Child class Constructor");
}
}

9
class Test{
public static void main(String[] args)
{
Child c = new Child();
}
}
Output:
Parent class Constructor
Child class Constructor
Super Keyword with parameterized Constructor:
class Base{
Base(int i){
System.out.println (“Base class Constructor Value=”+i);
}
}
class Derived extends Base{
Derived(){
super(100);
System.out.println(“Derived class Constructor");
}
}
class Test{
public static void main(String[] args)
{
Derived obj = new Derived();
}
}
Output:
Base class Constructor Value=100
Derived class Constructor

10
Final Keyword:
In Java, the final keyword is used to denote constants. It can be used with variables, methods,
and classes.
Once any entity (variable, method or class) is declared final, it can be assigned only once. That is,
 the final variable cannot be reinitialized with another value
 the final method cannot be overridden
 the final class cannot be extended

final variable: If a variable can be defined with final then that variable value cannot be changed
during the scope of program i.e., constant value.

Example-1 : Example-2:
class FinalDemo{ class Sample{
final int i=10; final int a=10;
void finalDemo(){ Sample()
i=i+10; {
System.out.println(“Value of i: ”+i); a=20;
} }
} }
class FinalTest{ class Test{
public static void main(String args[]) public static void main(String args[])
{ {
FinalDemo obj=new FinalDemo(); Sample obj=new Sample();
obj.finalDemo(); }
} }
} Output:
Output: can’t assign a value to final variable a
can’t assign a value to final variable i

final method: If a method can be defined with final then that method cannot be overridden

Example: class FinalTest{


class Parent{ public static void main(String args[]){
final void m1() Child obj=new Child();
{ obj.m1();
System.out.println(“Parent Class”); }
} }
} Output:
class Child extends Parent{ m1() in Child can’t override m1() in
void m1(){ Parent
System.out.println(“Child Class”);
}
}

11
final class: If a class can be defined with final then that class cannot be inherited.

Example: class FinalTest{


public static void main(String args[]){
final class Parent{
void m1()
Child obj=new Child();
{
obj.m1();
System.out.println(“Parent Class”);
}
}
}
}
class Child extends Parent{
void m1(){ Output:
System.out.println(“Child Class”); cannot inherit from final Parent
}
}

Abstraction in Java: Abstraction is a process of hiding the implementation details and showing
only functionality to the user.
Ex: sms, os, apps..etc.
There are two ways to achieve abstraction in java
 Abstract class
 Interface
Abstract class
 A class which is declared with the abstract keyword is known as an abstract class in Java.
 It can have Variables, abstract and non-abstract methods (method with the body).
 It can have constructors and static methods also.
 It can have final methods which will force the subclass not to change the body of the
method.
 If a method is declared with abstract keyword then it is called as abstract method.
 abstract method contains only declarations i.e., it doesn’t provide definition /
implementation of a method.
 If a class is having atleast one abstract method then class is called abstract class & it may
also have normal methods.
 Implementation of abstract method can be written in derived class only
 If a class contains complete definition for all methods then then is called concrete class
 Objects can’t be created / instantiated from the abstract class and can be created from
concrete class

12
Example:

abstract class A class AbstractDemo{


{ public static void main(String
abstract void display(); args[]){
} C c = new C();
abstract class B extends A{ c.show();
void display() }
{
}
System.out.println(“Abstract Method in A”);
}
abstract void show(); Output:
} Show Method in B
class C extends class B{ Abstract Method in A
void show(){
System.out.println(“Show Method in B”);
display();
}
}

Abstract Class vs Concrete Class vs Interface:

S. No Abstract Class Concrete Class

1 It is declared using abstract modifier No need of access modifier

2 It is not possible to create object for We can create object for concrete class
abstract class

3 Abstract class contains abstract Concrete class contains only concrete


methods and concrete methods also methods but not abstract methods

4 Abstract class can’t be declared as final Concrete class can be declared as final

S. No Abstract Class Interface

1 It doesn’t provide full abstraction i.e., It It provides full abstraction i.e., It contains
may contains concrete methods also only abstract methods

2 We can’t implement multiple We can implement multiple inheritance


inheritance

3 Every method present in abstract class Every method present in interface is by


need not be public & abstract default public & abstract

13
4 Every variable present in abstract class Every variable present in interface is
need not be public, static & final always public, static & final

5 Not necessary to initialize variables We should perform variable initialization


during declarations in abstract class during declaration otherwise will get
compilation error

Interfaces:
• Like a class, an interface can have methods and variables, but the methods declared in an
interface are by default abstract (only method signature, no body)
• An interface cannot be instantiated, but we can create a reference for interface.
• A class that implement interface must implement all the methods declared in the interface. To
implement interface use implements keyword.
• If a class implements an interface and does not provide method bodies for all methods specified
in the interface, then the class must be declared as abstract.
• If the subclass is overriding all the methods of an interface then it is called as implementation
class.
• A class can implement any number of interfaces.
• By default, each and every method in the interface is a public abstract.
• By default every variable in interface acts like public static final.
• We cannot create constructors in interface.
• We can use default method in interface. (Java 8)
• We can use static method in interface.(Java 9)
• Using interface we can achieve multiple inheritance.
• To declare an interface, use interface keyword
Syntax:
interface interface_name {
// declare fields // By default public static final
// declare methods // By default public abstract
}

14
Example-1:
interface Interface_Example{
public void test();
}
class Test implements InterfaceExample{
public void test(){
System.out.println ("Interface Method Implemented");
}
public static void main(String args[]){
Test p = new Test();
p.test();
}
}
Output:
Interface Method Implemented

Multiple Inheritance:

1)

2)

15
Example-2:
interface A{
int a=10;
void show();
}
interface B{
int b=20;
void show();
}
class C implements A,B{
int c;
public void show(){
c=A.a+B.b;
System.out.println(“A.a=“+A.a);
System.out.println(“B.b=“+B.b);
System.out.println(“C=“+c);
}
}
class Test{
public static void main(String args[]){
C obj = new C();
obj.show();
}
}

Output:
A.a=10
B.b=20
C=30

16
Example-2:
interface A
{
int a=10;
public void test();
}
class B
{
int b=20;
public void show()
{
System.out.println("class Method Implemented");
System.out.println("b=" + b);
}
}
class Sample extends B implements A
{
public void test()
{
System.out.println("Interface-A Method Implemented");
System.out.println("a=" + a);
}
}
public class Interface_example2
{
public static void main(String args[])
{
Sample p = new Sample();
p.test();
p.show();
}
}

INPUT / OUTPUT:

Interface-A Method Implemented


a=10
class Method Implemented
b=20

17
Packages in Java:

18

You might also like