[go: up one dir, main page]

0% found this document useful (0 votes)
11 views12 pages

Unit_3 Inheritence and Polymorphism KVN

The document covers key concepts of Object-Oriented Programming (OOP) in Java, focusing on inheritance and polymorphism. It explains various types of inheritance, the use of the 'super' keyword, and the differences between classes and interfaces. Additionally, it discusses method overloading and overriding, the final keyword, abstract classes, and the organization of classes into packages.

Uploaded by

examsgfgcwt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views12 pages

Unit_3 Inheritence and Polymorphism KVN

The document covers key concepts of Object-Oriented Programming (OOP) in Java, focusing on inheritance and polymorphism. It explains various types of inheritance, the use of the 'super' keyword, and the differences between classes and interfaces. Additionally, it discusses method overloading and overriding, the final keyword, abstract classes, and the organization of classes into packages.

Uploaded by

examsgfgcwt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 12

Object Oriented Programming with JAVA-NEP Page-1

Unit-3
Inheritance and Polymorphism
Inheritance is a mechanism in which one object acquires all the properties and
behaviors of a parent class. The new classes are created from the existing classes.
Inheritance represents a parent-child relationship.
“The process of deriving a new class from an existing class is called inheritance”. The
existing class is called super class or base class or parent class and the new class
is called sub class or derived class or child class. A child class contains all the
members (fields, methods and nested methods) of its base class and also its own
members.
 Code reusability and method overriding (runtime p olymorphism) are the important oop
paradigms achieved through inheritance. .
Syntax of Java Inheritance
The extends keyword indicates that a
class Subclass-name extends Superclass-name new class that is derived from an
existing class. The meaning of
{
"extends" is to increase the
//methods and fields functionality.
}

Types of Inheritance: Inheritance takes different forms:


1. Single inheritance: A sub class derived from one base class.
2. Multilevel inheritance: Creating a new class from a derived class.
3. Hierarchical inheritance: One base class and many sub classes.
1. Multiple inheritance: Inheritance having several super classes.
4. Hybrid inheritance: Combines single, hierarchical, multiple & multilevel
inheritance.

Note: Java doesn’t directly implement multiple and hybrid inheritance. However, they
are implemented using a secondary inheritance path in the form of interface.
Single Inheritance: A class derived from an existing class. This inheritance consists
of one base class and one derived class.
Syntax: class A extends B The keyword extends signifies that the
{ properties of class A are extended to the class
Variable declaration; B. The sub class B contains its variables and
Method declaration; methods and also that of the super class A.
}
Write a program to illustrate single inheritance.
import java.io.*;
class Parent
{
public void display()
{
System.out.println("TUMKUR");
}
}

Dept. of Computer Science, GFGC, Tiptur. II BSc (PCs/MCs), III Sem.


Object Oriented Programming with JAVA-NEP Page-2

public class Child extends Parent


{
public void show()
{
System.out.println("KARNATAKA");
}
}
class Demo
{
public static void main(String args[])
{
Child r=new Child ();
r. show ();
r. display();
}
}
A
Multilevel Inheritance class A
In multiple inheritance a new class is derived from {
an existing derived class i.e. a class is derived from :
B }
another derived class. In OOP a derived class is used
class B extends A
as a super class. Java supports this concept {
& uses it extensively in building its class library C :
}
Write a program to illustrate multilevel inheritance class C extends B
class Abc {
{ :
void show() }
{
System.out.println("PCs");
}
}
class Qrs extends Abc
{
void display()
{
System.out.println("MCs");
}
}
class Xyz extends Qrs
{
Xyz ()
{
System.out.println("BCA");
}
} PCs
public class Demo MCs
{ BCA
public static void main(String args[])
{
Xyz r=new Xyz ();
r.show();
r.display();
}

Dept. of Computer Science, GFGC, Tiptur. II BSc (PCs/MCs), III Sem.


Object Oriented Programming with JAVA-NEP Page-3

}
Hierarchical Inheritance: In hierarchical inheritance there is only one super class
and more than one subclasses.

Base class
A Class A is the base class for both B and C. Class B and
class C are subclasses of class A. Class B contains
characteristics of A and class C contains characteristics
B C of A. In other words B and C inherits the properties of A.
Derived classes

Write a program to illustrate hierarchical inheritance.


class Abc
{
void show()
{
System.out.println("BSc");
}
}
class Qrs extends Abc
{
void display()
{
System.out.println("BCA");
}
}
class Xyz extends Abc
{
Xyz ()
{
System.out.println("BCom");
}
}
public class Demo
{
public static void main(String args[])
{
Xyz r=new Xyz ();
r.show();
r.display();
}
}
The super keyword: If an object to super class is created, only super class members
are accessed but sub class cannot be accessed. If a subclass object is created, then
both super class and sub class methods are accessed. Hence in inheritance an object
to subclass is created. If super class and sub class members have the same name by
default sub class members are accessible. To access the super class members from
the sub class, keyword super is used.
The super keyword is used for two purposes
1. To refer super class variable, the super keyword is used as super.variable.
2. To refer super class method, the super keyword is used as super.method.
The super keyword in Java is a reference variable which is used to refer immediate
parent class object. Whenever an instance of subclass is created, an instance of
parent class is implicitly created which is referred by the variable ‘super’.

Dept. of Computer Science, GFGC, Tiptur. II BSc (PCs/MCs), III Sem.


Object Oriented Programming with JAVA-NEP Page-4

e.g.: class Vehicle


{
String color="white";
}
class Car extends Vehicle
{
String color="black";
void display()
{
System.out.println(color); //prints color of Car class
System.out.println(super.color); //prints color of Vehicle class
}
}
class Demo blac
{ k
public static void main(String args[]) whit
{
Car r=new Car ();
r. display();
}
}
Usage of Java super Keyword
super can be used to refer immediate parent class instance variable.
super can be used to invoke immediate parent class method.
super() can be used to invoke immediate parent class constructor.
Note: 1. Constructors are not inherited by child class, but the constructor of the super
class can be invoked.
2. In java, multiple and hybrid inheritance are supported through interface.

Interfaces: An interface is a type of class that defines only an abstract


method and final fields. This means that interface don’t specify any code to
implement these methods and data fields. An interface in java is a blueprint of
a class. It has static constants and abstract methods. The interface in Java is a
mechanism to achieve abstraction and multiple inheritance. Java does not
supports multiple inheritance
Syntax :
interface interfaceName
{ interface is the keyword & interfaceName is a valid
constant_declaration; identifier. constant declaration consists of final fields.
abstract methods; The abstract method contains only a list of methods
} without any functional body.
e.g.: interface Item
{
All methods in an interface are implicitly public &
static final int a = 100;
abstract.
abstract void display();
}
Implementing interface: Interfaces are used as “super classes” whose properties are
inherited by classes. A class that implements an interface must provide an
implementation for all the methods of the interface. The keyword implement is used to
specify that a class inherits behaviour from an interface and has the code for every
method of the interface. A class can implement multiple interfaces.

Dept. of Computer Science, GFGC, Tiptur. II BSc (PCs/MCs), III Sem.


Object Oriented Programming with JAVA-NEP Page-5

Syntax: class class_name implements interface_name


{
... Here, class implements an interface.
}

Difference between class and interface:

Class Interface
It contains instance variable, constants and It contains only constants and
instance method. abstract methods
It contains design & implementation of Interface contains pure design
code
Class can be instantiated Interface can’t be instantiated.
Class extends Interface implements
Keyword class is used Keyword interface is used
Constructors are used for initialization Constructor never used.
Methods are defined to perform a specific The methods in an interface are
action purely abstract

Polymorphism: Polymorphism is the ability of an object to take on many forms.


The most common use of polymorphism in OOP occurs when a parent class
reference is used to refer to a child class object. A real-life example of
polymorphism is a person can have different characteristics. Like a man at the
same time is a father, a husband & an employee

Types of polymorphism:

1. Method Overloading – This is an example of compile time (or static polymorphism)


2. Method Overriding – This is an example of runtime time (or dynamic
polymorphism):

Dept. of Computer Science, GFGC, Tiptur. II BSc (PCs/MCs), III Sem.


Object Oriented Programming with JAVA-NEP Page-6

3.
4.
5.
6.
7.

8.
9.
10.
Overloading methods:
The process of creating methods having same name, but different parameter
list is called methods overloading. Method overloading is used when objects
are required to perform similar task using different input parameters.
11.

e.g:
class Overloading
{
void sum(int a,long b)
{
System.out.println(a+b);
}
void sum(int a,int b,int c)
{
System.out.println(a+b+c);
}
}
Class Example
{
public static void main(String args[])
{ 40
Overloading obj=new Overloading(); 60
obj.sum(20,20);
obj.sum(20,20,20);
}
}
Overriding methods:
By defining a method in the sub class that has the same name, same
arguments with same data type as a method in the super class. When that
method is called, the method defined in the subclass is invoked and executed
instead of super class method. This is known as method overriding.
e.g: class Xyz
{
protected void display()
{
System.out.println(“BSc”);
}
}
class Pqr extends Xyz
{
void display()
{ Here the display() method of child class
System.out.println(“BCA”); overrides the display() method of the base
} class.
}
public class Demo
{ BCA
public static void main(String args[])
{
Pqr r=new Pqr ();
r.display();
}
}

Dept. of Computer Science, GFGC, Tiptur. II BSc (PCs/MCs), III Sem.


Object Oriented Programming with JAVA-NEP Page-7

The final keyword: The keyword final is used in 3 ways,


 A variable can be declared final, can be assigned only once & cannot be changed.
Attempts to change it will generate either a compile time error or an exception.
e.g: final float pi =3.142;
final int a=100;
 A method declared final cannot be overridden. When a method is made final, the
functionality of this method will never be altered. Hence it avoids method
overriding.

 A class declared final prevents inheritance. To prevent further derivation of a class


into sub classes, the keyword final is used with class. The class that can’t be
extended is called final class. All the methods of a final class are implicitly final
Difference between overloading and overriding

Overloading Overriding
It deals with multiple methods with the It deals with two methods, one in a parent
same name in the same class, but with class and another in child class that have
different argument list. the same name and same arguments.
Define a similar operation in different Define a similar operation in different ways
ways for different parameters. for different object types.
These methods are invoked depending These methods are invoked depending on
on the type of the arguments. the type of the objects.
Inheritance not needed It needs inheritance
Static methods can be overloaded Static methods cannot be overridden
private and final methods can be private and final methods cannot be
overloaded overridden

The finalizer () or finalize() method:


Java supports a concept called finalization, which is the opposite of initialization. Java
run-time is an automatic garbage collecting system. It automatically frees up the
memory resources used by the objects. But objects may hold other non-object
resources such as file description or windows system font or windows garbage
collection. The garbage collector can’t free these resources. For this, a finalizer()
method is used. This is similar to destructors in c++. This method can be added to
any class. The finalize method should explicitly define the task to be performed.
Syntax: finalize();

The abstract keyword:


The abstract keyword is used for both class and method.
If the class is declared as abstract, the programmer cannot create an object of that
class.
Note:
1. An abstract class cannot be instantiated, but it can be extended into subclasses.
2. Abstract constructor cannot be declared.
An abstract method means a method which has only declaration. The body of the
abstract method is not defined in abstract class but defined in child class.

Dept. of Computer Science, GFGC, Tiptur. II BSc (PCs/MCs), III Sem.


Object Oriented Programming with JAVA-NEP Page-8

Program to illustrate the use of abstract class and abstract method

abstract class Abc


{
int i=2023;
public abstract void display()
Abc()
{
System.out.println("TIPTUR");
}
}
class Pqr extends Abc
{
int i;
public void display()
{
System.out.println("BSc ");
}
}
class Demo
{ TIPTUR
public static void main(String args[]) BSc
{ 2023
Pqr r=new Pqr ();
r. display();
System.out.println(r.i)
}
}

Packages:
A Package is a collection of related classes and interfaces. It helps to organize
the classes into a folder structure and make it easy to locate and use them.
Packages act like a container for classes and interfaces and grouped according
to their functionality. Packages are similar to folders in computer. As folder can
hold subfolders, a package can have sub packages.
Note:
 When present, package must be the first non comment statement in the file.

 Java packages can be stored in compressed files called JAR files, allowing
classes to download faster as a group rather than one at a time.

 The access specifiers protected and default have access control on package
level. The protected member is accessible by classes within the same
package and its subclasses. The default access specifier is accessible by
classes in the same package.

Dept. of Computer Science, GFGC, Tiptur. II BSc (PCs/MCs), III Sem.


Object Oriented Programming with JAVA-NEP Page-9

Advantages of packages:
There are several advantages of using java packages:
 Make easy searching or locating of classes and interfaces.
 Avoids naming conflicts. If there are two classes with the name Student in
two packages, bca.Student and bsc.Student.
 Implement data encapsulation.
Types of Java packages:
Java packages are classified into 2 types,
1. Inbuilt packages or Java API packages
2. User defined packages.

Java API packages:


Java API provides a large no. of classes grouped into different packages
according to their functionality of the classes. It includes all java packages,
classes and interfaces, their methods, fields and constructors.

Java API package

lang util awt io net applet

The java.lang package supports language classes. java.lang include classes for
primitive data types, strings, mathematical functions, threads and exceptions.
java.lang is the default package in java.

java.util contains language utility classes like Date, Stack, Calendar etc
java.io contains i/o support classes. They provide facilities for the I/O operation on
data.
java.awt for implementing GUI. They include classes for windows, buttons, list, menu
etc
java.net contains classes for networking. They include classes for communicating with
LAN and internet servers.
java.applet contains classes for creating and implementing applets.

There are 2 ways of accessing the classes stored in a package.


1. import packagename . className;
e.g. : import java . util . Date;
Here import is the keyword that imports the class Date from the package util. All Date
class methods are directly used in our program.

2. import packagename . *;
e.g. : import java . util . *;
This imports all classes present in the util package.

Dept. of Computer Science, GFGC, Tiptur. II BSc (PCs/MCs), III Sem.


Object Oriented Programming with JAVA-NEP P a g e - 10

User defined package:


These packages are defined by the user by creating a directory with the name same
as the name of the package. Then create a class inside the directory

Steps to create the user defined package:


1. Create a directory, which has the same as PackageName.
2. Specify the package name with the help of package keyword.
3. Declare the package at beginning of file using PackageName
4. Create a java file in newly created directory
5. Save this file with same name (ClassName. java).
6. Define the class that is to be placed in the package and declare it public.
7. public class ClassName
{
class body
}
8. Compile the java file directory and run the individual package by using
java PackageName. ClassName
C:\jdk1.3\bin> MD PACK MD : Make Directory
C:\jdk1.3\bin> CD PACK CD: Change Directory
C:\jdk1.3\bin\pack> bin: Binary file also known as executable
file.
e.g.: Open the new file and enter the following code.
package pack;
public class Test
{
public static void main(String a[]) Save this file as Test. java inside the directory
{ pack.
System.out.println(“PUNEETH”); Compile the java program using javac Test. Java
} Run this program using java pack. Test
}
9. Change to previous level directory (cd ..)
10. Run the program.

Program to illustrate the use of user defined packages


package Package1;
public class Abc
{
public void display()
{
System.out.println("DHARANESH");
}
}
package Package2;
public class Xyz
{
int m=18;
public void show()
{

Dept. of Computer Science, GFGC, Tiptur. II BSc (PCs/MCs), III Sem.


Object Oriented Programming with JAVA-NEP P a g e - 11

System.out.println("INDIA");
System.out.println("m=”+m);
}
}

import Package1.Abc;
import Package2.*;
DHARANESH
class Test
INDIA
{
m=18
public static void main(String args[])
{
Abc obj1=new Abc();
Xyz obj2=new Xyz ();
obj1.display();
obj2.show();
}
}

Java Lang package: java lang package is automatically imported into all programs,
it contains classes and interfaces that are fundamental to all of java programming. It
is java’s most widely used package. It includes the following classes:

Boolean Byte Character Class


ClassLoader Compiler Double Float
InheritableThreadLoa Integer Long Math
d
Number Object Package Process
Runtime SecurityManage String StringBuffer
r
System Thread ThreadGroup ThreadLocal
Throwable Short Void
Converting primitive numbers to object numbers using constructor method

Calling constructor Description


Integer p = new Integer(i) -> Primitive integer to Integer object.
Float q = new Float(f) -> Primitive float to Float object.
Long L= new Long(l) -> Primitive long to Long object.
Double d = new Double(k) -> Primitive double to Double object.

Wrapper classes: Java uses simple data types, such as int and char for performance
reason. These data types are not the part of the object hierarchy. Primitive data types
may be converted into object types by using the wrapper classes, contained in the java.lang
package. The following table shows the simple data type and their corresponding wrapper class types.
Simple type Wrapper classes
boolean Boolean The wrapper classes have a number
of unique methods for handling
char Character
primitive data types and objects.
int Integer
float Float
long Long
double Double

Dept. of Computer Science, GFGC, Tiptur. II BSc (PCs/MCs), III Sem.


Object Oriented Programming with JAVA-NEP P a g e - 12

string String , StringBuffer

Note: The automatic conversion of primitive data types into its equivalent Wrapper
type is known as auto boxing and opposite operation is known as unboxing. For
example, converting an int to an Integer, a double to a Double and so on.

Java.util Package: Java util package contains collection framework, collection


classes, classes related to date and time, event model, internationalization, and
miscellaneous utility classes. On importing this package, we can access all
these classes and methods. AWT package contains the components like
buttons, textfields, labels etc. The classes that extends Container class such as
Frame, Dialog and Panel.
The import is a keyword which is used for importing a Java class or entire Java package.
e.g.: import java.util.Calendar; imports Calendar class from util package.

To import all the classes from util package, the import statement should
be import java.util.* ;

Uses of java.util package


1. It can be used for Java collections.
2. It can be used for internationalization support by using classes from
java.util package.
3. It can be used for random number generation.
4. It can be used for string parsing.
5. It can be used for base 64 encoding and decoding.

The instanceof operator:


The instanceof operator is used to test whether the object is an instance of
the specified type (class or subclass or interface). The instanceof operator
compares the instance with type. It returns either true or false. If the
instanceof operator applied with any variable that has null value, it returns
false.
Syntax: objectName instanceOf className;

*******

Dept. of Computer Science, GFGC, Tiptur. II BSc (PCs/MCs), III Sem.

You might also like