Unit 3

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 77

UNIT III – Inheritance, Abstraction and

Interfaces
Syllabus
• Inheritance Basic ,Types of inheritance, Member access rules, Usage of
super key word, Method overriding, Using final,
• Abstract classes, Differences between abstract classes and interfaces,
Defining an interface, Implementing interface, Applying interfaces,
Variables in interface and Extending interfaces.
• Defining , creating and accessing a package ,Importing packages ,Access
control in package
Inheritance-Introduction
• Inheritance is an important feature of object oriented programming.

• Inheritance can be defined as the process where one class acquires

the properties methods and fields of another class.

• The class which inherits the properties of other is known as

subclass/derivedclass/child class

• the class whose properties are inherited is known as

superclass/baseclass/parentclass.

• Inheritance provides the idea of reusability, i.e., a code once written

can be used again and again in a number of new classes


extends Keyword :
• extends is the keyword used to inherit the
properties of a class.
• syntax of extends keyword.
Types of Inheritance
• Inheritance is generally of five types : single level, multilevel,
multiple, hierarchical and hybrid.
Single-level Inheritance
• In single level inheritance, there is just one base and one
derived class. It is represented as follows:
Multilevel Inheritance
• In multilevel inheritance, there is one base
class and one derived class at the same time
at one level.
• At the next level, the derived class becomes
base class for the next derived class and so on.
This is shown as:
The class A and class B together form one
level, class B and class C together form
another level and so on.
For class B, class A is the parent and for class
C, class B is the parent; thus in this inheritance
level, A can be called the grandparent of class
C, and class C the grandchild of class A
Multiple Inheritance
• In a multiple inheritance, a child can have more than one
parent, i.e., a child can inherit properties from more than one
class.
• Java does not support Multiple inheritance ,to implement this
we can use the concept of interfaces
• Unfortunately, Java does not support the
multiple inheritances through classes though
it supports using interfaces
• That is, in Java one cannot write the following
syntax:
class A { } class B { }
class C extends A extends B{ }
Hierarchical Inheritance
• In this type of inheritance, multiple classes
share the same base class.
• That is, n number of classes inherit the
properties of one common base class.
• The derived classes may also become base
classes for other classes.
Hybrid Inheritance
• Hybrid Inheritance is a combination of
both Single Inheritance and Multiple
Inheritance.
• Since in Java Multiple Inheritance is not
supported directly we can achieve Hybrid
inheritance also through Interfaces only.
Why use inheritance in java
• For Method Overriding (so runtime polymorphism
can be achieved).
• For Code Reusability.
Super Keyword
• The super keyword in java is a reference variable
that is used to refer parent class objects.
• The keyword “super” came into the picture with
the concept of Inheritance.
• Whenever the base class version of the function
is called which is overridden in the derived class,
the super keyword can be used.
• The super keyword always refers to the
immediate base class
class SuperKeyword {
int a = 120;
}
class Keyword extends SuperKeyword {
int a = 180;
void display() {
System.out.println(“Value of a is: " + super.a); }
}
class SuperKeywordforVariable{
public static void main(String[] args) {
Keyword k = new Keyword();
k.display();
}}
class Base {
void message() {
System.out.println("This is Base class"); }
}
class Derived extends Base {
void message() {
System.out.println("This is derived class"); }
void display() {
message(); // call current class message() method
super.message(); // call parent class message() method
} }
class SuperKeywordforMethod{
public static void main(String args[]) {
Derived d = new Derived();
d.display(); } }
class Parent {
Parent() { System.out.println("Parent class Constructor");
} }
class Child extends Parent {
Child() {
super(); // call parent class constructor
System.out.println(“Child class Constructor");
} }
class SuperKeywordforConstructor{
public static void main(String[] args) {
Child c = new Child();
} }
class Base {
Base( ) {
System.out.println("insideparent“);
}
}
class Derived extends Base {
int x;
Derived(int x1) { public class ConstructorEg{
public static void main(String[]
super( );
args) {
x= x1; }
Derived d = new Derived(10);
void Display( ) { d.Display();
System.out.println("x = "+x); }}
} o/p:inside parent
} x = 10
Access Specifiers(protected Keyword)

class P{
protected int a=10;
void dis( ){ System.out.println("this is parent class variable"+a); }
}

class C extends P{
void dis1( ){ System.out.println("this is child class variable"+a); }
}
class Main{
public static void main(String[] args){
C o=new C();
o.dis();
o.a=20;
o.dis1();
}}
Method Overriding
• In method overriding, a base class method is
overridden in the derived class.
• That is, the same method is written with the
same signature as of the base class method but
different implementation.
• In method overloading, arguments and type of
arguments are used to distinguish between two
functions, but in method overriding no such
distinction can be made.
• When a method in a subclass has the same name, same
parameters or signature and same return type(or sub-type)
as a method in its super-class, then the method in the
subclass is said to override the method in the super-class.
• Method overriding is one of the way by which java
achieve Run Time Polymorphism
• The version of a method that is executed will be
determined by the object that is used to invoke it.
• This process in which call to the overridden method is
resolved at runtime is known as Dynamic method dispatch
• In method overriding, the signature of the two methods
must match. This is shown in the program given below.
Class A{
void dis(){
System.out.println(“this is class A”);
}}
Class B extends A{
void dis(){
System.out.println(“this is class B”);
}}
Class Demo{
P.S.V.main(String args[]){
B b=new B();
b.dis();
}}
Class A{
void dis(){
System.out.println(“this is class A”);
}}
Class B{
void dis(){
System.out.println(“this is class B”);
}}
Class Demo{
P.S.V.main(String args[]){
B b=new B();
b.dis();
A a=new A();
a.dis();
}}
o/p: this is class B
this is class A
Usage of Java Method Overriding
• Method overriding is used to provide the specific
implementation of a method which is already provided
by its superclass.
• Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
• The method must have the same name as in the parent
class
• The method must have the same parameter as in the
parent class.
• There must be an IS-A relationship (inheritance).
Dynamic Method Dispatch
• Dynamic method dispatch is the mechanism by which a
call to an overridden method is resolved at run time,
rather than compile time.
• Binding is the process of linking the function call with the
place where function definition is actually written so that
when a function call is made, it can be ascertained where
the control has to be transferred.
• Binding is also called linking, and is of two types:
1. Static binding
2. Dynamic binding.
1)Static binding :When at compile time, it is known which
function will be called in response to a function call, the
binding is said to be static binding, compile time binding or
early binding
2)Dynamic Binding:At run time, the decision is taken as to which
function is to be called in response to a function call. This type
of binding is known as late binding, runtime binding or
dynamic binding.
• When an overridden method is called through a superclass
reference, Java determines which
version(superclass/subclasses) of that method is to be
executed based upon the type of the object being referred to
at the time the call occurs. Thus, this determination is made
at run time.
• At run-time, it depends on the type of the object being
referred to (not the type of the reference variable) that
determines which version of an overridden method will be
executed
• A superclass reference variable can refer to a subclass object.
This is also known as upcasting. Java uses this fact to resolve
calls to overridden methods at run time.
class A{
void dis(){
System.out.println(“class A");}
}

class B extends A{
void dis(){
System.out.println(“class B");}

public static void main(String args[]){


A a = new B(); //upcasting
a.dis();

A a1=new A();
a1.dis();
}
}
o/p:class B
class A {
void dis() {
System.out.println("Inside A's method");
}
}
class B extends A {
void dis() {
System.out.println("Inside B's method");
}
}
class C extends A
{
void dis() {
System.out.println("Inside C's method");
}
}
class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A ref_var; // obtain a reference of type A
ref_var = a; // ref refers to an A object
ref_var.dis(); // calling A's dis()
ref_var = b; // now ref refers to a B object
ref_var.dis(); // calling B's dis()
ref_var = c; // now ref refers to a C object

ref_var.dis(); // calling C's dis()


}}

o/p: Inside A's method


Inside B's method
Inside C's method
In Java, we can override methods only, not the variables(data members), so
runtime polymorphism cannot be achieved by data members. For example :
class A {
int x = 10;
}
class B extends A {
int x = 20;
}
class Demo {
public static void main(String args[]) {
B b=new B();
A a = new A();
A ref;
ref=a;
System.out.println(ref.x);
ref=b;
System.out.println(ref.x);
}}
O/p:10
10
Interfaces
• An interface is just like Java Class, but it only has abstract
methods.
• An interface is a specification of method prototypes.
• Java uses Interface to implement multiple inheritance.
• A Java class can implement multiple Java Interfaces. All
methods in an interface are implicitly public and abstract
• A class that implements an interface must implement all
the methods declared in the interface.
• An interface is declared by using the “interface” keyword.
It provides total abstraction; means all the methods in an
interface are declared with the empty body
• Syntax:
interface interface_name{
…………….
// declare methods that abstract
………….
}
Ex:
interface MyInter{
void connect();
void disconnect();
void quit();
}
relationship between classes and interfaces
(A)a class extends another class
(B) a class implements an interface.
(C) an interface extends another interface,

(A) (B) (C)


//Implementing interfaces
interface InterfaceExample{
void print();
}

class Demo implements InterfaceExample{


public void print(){
System.out.println("Hello");
}
public static void main(String args[]){
InterfaceExample obj = new Demo();
obj.print();
}
}
o/p:Hello
Multiple inheritance in Java by interface

• If a class implements multiple interfaces, or an


interface extends multiple interfaces, it is
known as multiple inheritance.
interface A{
void print();
}
interface B{
void show();
}
class Demo implements A,B{
public void print(){
System.out.println("Hello"); }
public void show(){
System.out.println("Welcome"); }

public static void main(String args[]){


Demo obj = new Demo();
obj.print();
obj.show();
}
}
o/p:Hello
Interface inheritance
//A class implements an interface, but one interface extends another interface.
interface A{
void print(); }

interface B extends A{
void show(); }

class Demo implements B{


public void print(){
System.out.println("Hello");}
public void show(){
System.out.println("Welcome");}

public static void main(String args[]){


Demo obj = new Demo();
obj.print();
obj.show();
Abstraction
• Abstraction is a process of hiding the
implementation details and showing only
functionality to the user.
• Nothing but it shows only essential things to
the user and hides the internal details

• Two Ways to achieve Abstraction


1. Interface
2. Abstract class
Interface Vs Abstract Class
• Toyota • Registration No
• Hyundai • Fuel Tank
• Volkswagen • Steering
• Ford – Manual Steering
• Suzuki – Power Steering
• Tata Nexon – Electric Steering
• Mercedes Benz • Breakes
• Kia – Hydraulic breakes
• Tesla – Gas breakes
Abstract class
• A class which is declared with the abstract keyword is
known as an abstract class.
• An abstract class can have abstract and non-abstract
methods
Syntax of abstract class
• abstract class A{ }
Abstract Method:
• A method which is declared as abstract and does not
have implementation is known as an abstract method.
Syntax of abstract method
• abstract void dis(); //no implementation
Rules:
• An abstract class must be declared with an
abstract keyword.
• It can have abstract and non-abstract
methods.
• It cannot be instantiated.
• 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.
abstract class Super{
abstract void show(); //Abstract method
final void dis(){ // Non-Abstract method
System.out.println(“inside super class”);}
}

class Sub extends Super{


void show(){
System.out.println(“Abstract classes"); }

public static void main(String args[]){


Super obj = new Sub();
obj.show();
obj.dis();
}
}
o/p:Abstract classes
inside super class
abstract class A{
abstract void dis();
}
class B extends A{
void dis1(){
System.out.println("class B");
}
}
class Demo{
public static void main(String args[]){
A a=new B();
a.dis1();
}
}
o/p://----------Note:error occurs ---no overriding-----//
>>>>Compile by: javac Demo.java
>>>>.40.1/Demo.java:3: error: B is not abstract and does not override abstract method dis() in A
class B extends A{
^
1 error
//Abstract classes using constructors
abstract class A {
A() {
System.out.println(“A’s constructor");
}
abstract void dis();
}
class B extends A{
B() {
System.out.println(“B’s constructor ");
}
Void dis() { System.out.println(“B’s dis() method "); }
}
class Main {
public static void main(String args[]) {
A a = new B();
}
}
o/p: A’s constructor
Getter and Setter
Package in Java
Introduction:
• In java, programmers can create several classes
&Interface. After creating these classes and interface, it
is better if they are divided into some groups
depending on their relationship.
• Thus, the classes and interface which handle similar or
same task are put into the same directory or folder, which
is also known as package.
• Packages act as “containers” for classes. A package
represents a directory that contain related group of
classes & interface
• Packages are used in Java in order to prevent naming
conflicts, to control access, to make searching/locating and
usage of classes,interfaces, enumerations and annotations
easier, etc.
• A package provides a mechanism for grouping a variety of
similar types of classes, interfaces and sub-packages.
• Grouping is based on functionality.
• Package names are dot separated, e.g., java.lang.
• Resolving naming conflict of classes by prefixing the class
name with a package name.
• com.zzz.Circle and com.yyy.Circle are two distinct classes
Advantage of Java Package
• 1) Java package is used to categorize the
classes and interfaces so that they can be
easily maintained.
• 2) Java package provides access protection.
• 3) Java package removes naming collision.
TYPES OF PACKAGES

• There are basically 2 types of java packages.


They are as follow :
I. System Packages or Java API
II. User Defined Packages.
SYSTEM PACKAGES /JAVA API

• As there are built in methods , java also provides inbuilt


packages which contain lots of classes and interfaces.
• These classes inside the packages are already defined &
we can use them by importing relevant package in our
program
• Java has an extensive library of packages, a programmer
need not think about logic for doing any
task. For everything, there are the methods available
in java
• java.lang - Contains classes for primitive
types, strings, mathfunctions, threads, and
exception
• java.util - Contains classes such as vectors,
hash tables, date etc.
• java.io - Stream classes for I/O
• java.awt - Classes for implementing GUI –
windows, buttons,menus etc.
• java.net - Classes for networking
• java. Applet - Classes for creating and
implementing applets
USER DEFINED PACKAGES :
• The users of the Java language can also create their own packages.
They are called user-defined packages. User defined packages can
also be imported into other classes & used exactly in the same way as
the Built in packages.
i) Creating User Defined Packages
Syntax :
package packageName;
public class className
{
-------------
// Body of className
------------
}
• We must first declare the name of the package using the package
keyword followed by the package name.
This must be the first statement in a Java source file. Then define a
STEPS FOR CREATING PACKAGE :
To create a user defined package the following steps
should be involved :-
1: Declare the package at the beginning of a file using
the syntax :-
package packageName;
2: Define the class that is to be put in the package &
declare it public.
3: Create a subdirectory under the directory where the
main source files are stored.
4: Store the listing as the classname.java file in the
subdirectory created.
5: Compile the file. This create .class file in the
subdirectory.
Example
package p1;
public class C1{
public static void main(String args[]){
System.out.println("package creation");
}
}
How to compile java package
• javac -d directory javafilename
• Ex:javac -d . C1.java (The -d switch specifies
the destination where to put the generated
class file)
How to run java package
• java directory.javafilename
• Ex:java p1.C1
How to access package from another package?
• There are three ways to access the package
from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
• If you use package.* then all the classes and
interfaces of this package will be accessible
but not subpackages.
• The import keyword is used to make the
classes and interface of another package
accessible to the current package
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
2) Using packagename.classname
If you import package.classname then only declared class of this package will be
accessible.

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
3)Using fully qualified name
• If you use fully qualified name then only
declared class of this package will be
accessible. Now there is no need to import. But
you need to use fully qualified name every time
when you are accessing the class or interface.
• It is generally used when two packages have
same class name e.g. java.util and java.sql
packages contain Date class.
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Creating Sub packages
• create a sub package p2 within our existing
java package p1. Then we will modify our code
as

• Compile the file


• To execute the code mention the fully
qualified name of the class i.e. the package
name followed by the sub-package name
followed by the class name –
The END
Final Keyword for class
final class Main{ } Note:
class Demo extends Main{ for Final keyword
refer UNIT-1
void demo () {
System.out.println ("My Method");
}
public static void main (String args[]) {
Demo obj = new Demo ();
obj.demo ();
}}
Class A{
Final Void show(){//method declared as final
System.out.println(“class A”);
}}
Class B extends A{
Void show(){
System.out.println(“class B”);
}}
Class Demo{
Public static void main(String args[]){
B b=new B();
B.show();
}}
o/p:compile time error
Static and default method in Interface
interface Drawable{
void draw();
default void msg() {
System.out.println("default method");}
static int cube(int x) {
return x*x*x;}
}

class Rectangle implements Drawable{


public void draw(){
System.out.println("drawing rectangle");}
}
class TestInterfaceDefault{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
d.msg();
System.out.println(Drawable.cube(3));

You might also like