0% found this document useful (0 votes)
4 views35 pages

Unit 2

The document covers key concepts of Java programming, including inheritance, polymorphism, and the use of interfaces and packages. It explains inheritance types, the super keyword, and the final keyword, as well as method overloading and overriding. Additionally, it discusses abstract classes and methods, emphasizing the importance of these concepts in object-oriented programming.

Uploaded by

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

Unit 2

The document covers key concepts of Java programming, including inheritance, polymorphism, and the use of interfaces and packages. It explains inheritance types, the super keyword, and the final keyword, as well as method overloading and overriding. Additionally, it discusses abstract classes and methods, emphasizing the importance of these concepts in object-oriented programming.

Uploaded by

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

JAVA-UNIT-2

Inheritance – Inheritance types, super keyword, preventing


inheritance: final classes and methods.
Polymorphism – Method overloading and Method overriding,
abstract classes and methods.
Interfaces- Interfaces Vs Abstract classes, defining an interface,
implement interfaces, accessing implementations through
interface references, extending interface, inner class.
Packages- Defining, creating and accessing a package, importing
packages.

1. Inheritance
Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviours of a parent object.

It is an important part of OOPs (Object Oriented Programming system).

Inheritance represents the IS-A relationship, also known as parent-child


relationship.

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
the parent class. Moreover, you can add new methods and fields in your current
class also.

Terms used in Inheritance


1. Class: A class is a group of objects which have common properties. It is
a template or blueprint from which objects are created.
2. Sub Class/Child Class: Subclass is a class which inherits the other class.
It is also called a derived class, extended class, or child class.
3. Super Class/Parent Class: Superclass is the class from where a subclass
inherits the features. It is also called a base class or a parent class.
4. Reusability: As the name specifies, reusability is a mechanism which
facilitates you to reuse the fields and methods of the existing class when
you create a new class. You can use the same fields and methods already
defined in the previous class.

Syntax of Inheritance

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. The meaning of "extends" is to increase the
functionality.

Diagram

Example

class Animal {

// methods and fields


}

// use of extends keyword

// to perform inheritance

class Dog extends Animal {

// methods and fields of Animal

// methods and fields of Dog

Example

class Employee{

float salary=40000;

class Programmer extends Employee{

int bonus=10000;

public static void main(String args[]){

Programmer p=new Programmer();

System.out.println("Programmer salary is:"+p.salary);

System.out.println("Bonus of Programmer is:"+p.bonus);

Output:

Programmer salary is: 40000.0

Bonus of programmer is: 10000

2. Types of inheritance in java


There are 5 types of Inheritance in java are:

1. Single inheritance.
2. Multi-level inheritance.
3. Multiple inheritance.
4. Hierarchical Inheritance.
5. Hybrid Inheritance.

On the basis of class, there can be three types of inheritance in java: single,
multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported through


interface only.

1. Single Inheritance

When a class inherits another class, it is known as a single inheritance.


In the example given below, Dog class inherits the Animal class, so there is the
single inheritance.

Example Program
class Animal{

void eat(){

System.out.println("eating...");}

class Dog extends Animal{

void bark(){

System.out.println("barking...");}

class TestInheritance{

public static void main(String args[]){

Dog d=new Dog();

d.bark();

d.eat();

Output

barking...

eating...

2. Multilevel Inheritance
When there is a chain of inheritance, it is known as multilevel inheritance.

As you can see in the example given below, BabyDog class inherits the Dog
class which again inherits the Animal class, so there is a multilevel inheritance.

Example Program

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...
3. Hierarchical Inheritance

When two or more classes inherits a single class, it is known as hierarchical


inheritance.

Example Program

In the example given below, Dog and Cat classes inherits the Animal class, so
there is hierarchical inheritance.

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();

Output
meowing...

eating...

3. 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.

Usage of Java 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.

1) super is used to refer immediate parent class instance variable

We can use super keyword to access the data member or field of parent class. It
is used if parent class and child class have same fields.

Example Program

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();

}}

Program Explanation:

In the above example, Animal and Dog both classes have a common property
color. If we print color property, it will print the color of current class by
default. To access the parent property, we need to use super keyword.

2) super can be used to invoke parent class method

The super keyword can also 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.

Example Program

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();

}}

Program Explanation:

In the above example Animal and Dog both classes have eat() method if we call
eat() method from Dog class, it will call the eat() method of Dog class by
default because priority is given to local.

To call the parent class method, we need to use super keyword.

3) super() can be used to invoke immediate parent class constructor

The super keyword can also be used to invoke the parent class constructor.

Example Program

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();

}}

4. final keyword in JAVA


The final keyword in java is used to restrict the user.

The final keyword is useful when you want a variable to always store the same
value, like PI (3.14159...).

The final keyword is called a "modifier".

The java final keyword can be used in many contexts.

final can be:

1. variable

2. method

3. class
1. final variable:

In Java, a final variable is a variable whose value cannot be changed once it is


assigned.
Once a value is assigned to a final variable, it becomes a constant and cannot be
modified later in the program.

To declare a final variable in Java, the keyword "final" is used before the
variable declaration.

Example program of final variable

class Bike{

final int speedlimit=90;//final variable

void run(){

speedlimit=400;

public static void main(String args[]){

Bike obj=new Bike();

obj.run();

}//end of class

Output:

Compile Time Error

In above program there is a final variable speedlimit, we are going to change the
value of this variable, but It can't be changed because final variable once
assigned a value can never be changed.
2. final method

In Java, a final method is a method that cannot be overridden by subclasses.

Once a method is declared as final, it cannot be changed or overridden in any of


its subclasses.

To declare a method as final in Java, the keyword "final" is used before the
method signature.

Example program 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();

Output:

Compile Time Error

3. Java final class


In Java, a final class is a class that cannot be extended or subclassed by any
other class.

Once a class is declared as final, it cannot be extended, which means that no


other class can inherit from it.

To declare a class as final in Java, the keyword "final" is used before the class
declaration.

Example program of final class

final class Bike{}

class Honda1 extends Bike{

void run(){

System.out.println("running safely with 100kmph");

public static void main(String args[]){

Honda1 honda= new Honda1();

honda.run();

Output:

Compile Time Error

5. Polymorphism in Java
Polymorphism in Java is the task that performs a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs.
The word "poly" means many and "morphs" means forms. So polymorphism
means many forms.

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


In Java, polymorphism refers to the ability of a class to provide different
implementations of a method, depending on the type of object that is passed to
the method.

There are two types of polymorphism in Java:

1. Compile-time polymorphism (Method Overloading)

2. Run-time polymorphism. ( Method Overriding)

We can perform polymorphism in java by method overloading and method


overriding.

Example Program

class Shapes {

public void area() {

System.out.println("The formula for area of ");

class Triangle extends Shapes {

public void area() {

System.out.println("Triangle is ½ * base * height ");

class Circle extends Shapes {

public void area() {

System.out.println("Circle is 3.14 * radius * radius ");


}

class Main {

public static void main(String[] args) {

Shapes myShape = new Shapes(); // Create a Shapes object

Shapes myTriangle = new Triangle(); // Create a Triangle object

Shapes myCircle = new Circle(); // Create a Circle object

myShape.area();

myTriangle.area();

myShape.area();

myCircle.area();

Output

The formula for the area of the Triangle is ½ * base * height

The formula for the area of the Circle is 3.14 * radius * radius

1. Compile-time polymorphism in JAVA

It is also known as static polymorphism. This type of polymorphism is


achieved by function overloading/method overloading or operator
overloading.

Note: But Java doesn’t support the Operator Overloading.

1. Method Overloading
If a class has multiple methods having same name but different in parameters, it
is known as Method Overloading.

If we have to perform only one operation, having same name of the methods
increases the readability of the program.

Functions can be overloaded by changes in the number of arguments or/and a


change in the type of arguments.

Example 1: Changing no. of arguments

class Adder{

static int add(int a,int b){return a+b;}

static int add(int a,int b,int c){return a+b+c;}

class TestOverloading1{

public static void main(String[] args){

System.out.println(Adder.add(11,11));

System.out.println(Adder.add(11,11,11));

}}

Output: 22 33

Example 2: Changing data type of arguments


class Adder{

static int add(int a, int b){return a+b;}

static double add(double a, double b){return a+b;}

class TestOverloading2{

public static void main(String[] args){


System.out.println(Adder.add(11,11));

System.out.println(Adder.add(12.3,12.6));

}}

Output: 22 24.9

2. Runtime Polymorphism in JAVA/ Dynamic Method Dispatch/ Method


Overriding

It is also known as Dynamic Method Dispatch. It is a process in which a


function call to the overridden method is resolved at Runtime. This type of
polymorphism is achieved by Method Overriding.

If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.

In other words, If a subclass provides the specific implementation of the method


that has been declared by one of its parent class, it is known as method
overriding.

Example Program
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 Test{

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());

6. Method Overloading Vs Method Overriding in JAVA


S.No Method Overloading Method Overriding
1 Method overloading is used to increase Method overriding is used to
the readability of the program. provide the specific
implementation of the method
that is already provided by its
super class.
2 Method overloading is Method overriding occurs in
performed within class. two classes that have IS-A
(inheritance) relationship.
3 In case of method In case of method
overloading, parameter must be overriding, parameter must be
different. same.
4 Method overloading is the example Method overriding is the
of compile time polymorphism. example of run time
polymorphism.
5 In java, method overloading can't be Return type must be same or
performed by changing return type of covariant in method overriding.
the method only. Return type can be
same or different in method
overloading. But you must have to
change the parameter.

7. Abstract Classes & Abstract Methods in Java


Abstract Class: A class which is declared as abstract is known as an abstract
class. It can have abstract and non-abstract methods (method with the body). It
needs to be extended and its method implemented.

Abstract method: can only be used in an abstract class, and it does not have a
body. The body is provided by the subclass (inherited from).

Abstraction

Abstraction is a process of hiding the implementation details and showing only


functionality to the user.

It shows only essential things to the user and hides the internal details.

An abstract class must be declared with an abstract keyword.

If the Child class is unable to provide implementation to all abstract methods


of the Parent class then we should declare that Child class as abstract so that
the next level Child class should provide implementation to the remaining
abstract methods.

Syntax of abstract class

abstract classA{ }

Syntax of abstract method


abstract void printStatus();//no body and abstract

Example Program1: Abstract class that has an abstract method


abstract class Bike{

abstract void run();

class Honda4 extends Bike{

void run(){System.out.println("running safely");}

public static void main(String args[]){

Bike obj = new Honda4();

obj.run();

Example Program2: Abstract class that has an abstract method

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()+" %");

}}

8. Interfaces in JAVA
The interface in Java is a mechanism to achieve abstraction.

There can be only abstract methods in the Java interface, not method body.

It is used to achieve abstraction and multiple inheritance in Java.

An interface in Java is a blueprint of a class. It has static constants and abstract


methods.

Interfaces can have abstract methods and variables. It cannot have a method
body.

Java Interface also represents the IS-A relationship.

Syntax

interface {
// declare constant fields
// declare methods that abstract
// by default.
}

Advantages of Interfaces in JAVA

1. It is used to achieve total abstraction.


2. Since java does not support multiple inheritances in the case of class, by
using an interface it can achieve multiple inheritances.
3. Any class can extend only 1 class but can any class can implement
infinite number of interfaces.
The relationship between classes and interfaces

Example Program: Interface

//In this example, the Printable interface has only one method, and its
implementation is provided in the A6 class.

interface printable{

void print();

class A6 implements printable{

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


public static void main(String args[]){

A6 obj = new A6();

obj.print();

Output: Hello

Multiple inheritance in Java using interface

If a class implements multiple interfaces, or an interface extends multiple


interfaces, it is known as multiple inheritance.

Example Program: Multiple inheritance in Java using interface

interface Printable{

void print();

interface Showable{

void show();

}
class A7 implements Printable,Showable{

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

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

public static void main(String args[]){

A7 obj = new A7();

obj.print();

obj.show();

Output

Hello

Welcome

9. Abstract classes Vs Interfaces in JAVA


Abstract class Interface
1) Abstract class can have abstract Interface can have only abstract methods.
and non-abstract methods. Since Java 8, it can have default and static
methods also.
2) Abstract class doesn't support Interface supports multiple inheritance.
multiple inheritance.
3) Abstract class can have final, non- Interface has only static and final variables.
final, static and non-static
variables.
4) Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.
5) The abstract keyword is used to The interface keyword is used to declare
declare abstract class. interface.
6) An abstract class can extend An interface can extend another Java
another Java class and implement interface only.
multiple Java interfaces.
7) An abstract class can be extended An interface can be implemented using
using keyword "extends". keyword "implements".
8) A Java abstract class can have Members of a Java interface are public by
class members like private, protected, default.
etc.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

10. Extending an Interface in JAVA


In java, an interface can extend another interface. When an interface wants to
extend another interface, it uses the keyword extends.

The interface that extends another interface has its own members and all the
members defined in its parent interface too.

The class which implements a child interface needs to provide code for the
methods defined in both child and parent interfaces, otherwise, it needs to be
defined as abstract class.

Example Program

interface ParentInterface{

void parentMethod();

interface ChildInterface extends ParentInterface{

void childMethod();

}
class A implements ChildInterface{

public void childMethod()

System.out.println("Child Interface method!!");

public void parentMethod()

System.out.println("Parent Interface mehtod!");

public class Test {

public static void main(String[] args) {

A obj = new A();

obj.childMethod();

obj.parentMethod();

11. Inner Classes (Nested Classes) in JAVA


In Java, an inner class is a class that is declared inside another class.

Inner classes are also known as nested classes because they are nested within
another class.
Inner classes can access the members of the enclosing class (outer class) as if
they were their own members.

This means that an inner class can access the private fields and methods of the
outer class.

Inner classes provide a way to logically group classes and interfaces in one
place and can increase encapsulation and code readability.

Types of Inner Classes in JAVA

There are four types of inner classes in Java,

1. Member Inner Class: This is a non-static inner class that is declared


inside a class without using the static keyword. It can access all the
members of the enclosing class, including private members.

2. Static Nested Class: This is a static inner class that is declared inside a
class using the static keyword. It can access only the static members of
the enclosing class.

3. Local Inner Class: This is a class that is declared inside a method or a


block of code. It has access to the final variables of the method or block
and the members of the enclosing class.
4. Anonymous Inner Class: This is a class that is declared without a name
and is used to create objects of a class or interface. It is typically used for
event handling or to implement interfaces.

Syntax of Inner class


class Java_Outer_class{

//code

class Java_Inner_class{

//code

}
}

Example Program

class OuterClass

int x = 10;

class InnerClass

int y = 5;

public class Main

public static void main(String[] args)

OuterClass outerobj = new OuterClass();

OuterClass.InnerClass innerobj = outerobj.new InnerClass();

System.out.println(outerobj.x);

System.out.println(innerobj.y);

}
}

Output: 10 5

12. Java Packages


A java package is a group of similar types of classes, interfaces and sub-
packages.

We use packages to avoid name conflicts, and to write a better maintainable


code.

Package names are like directory structure.

The library is divided into packages and classes. Meaning you can either
import a single class (along with its methods and attributes), or a whole package
that contain all the classes that belong to the specified package.

To use a class or a package from the library, you need to use


the import keyword:

Syntax

import package.name.Class; // Import a single class


import package.name.*; // Import the whole package

Example of java package

The package keyword is used to create a package in java.

//save as Simple.java

package mypack;

public class Simple{

public static void main(String args[]){

System.out.println("Welcome to package");

} }
Compilation:

javac -d directory javafilename


ex: javac –d D:\javap\ Simple.java (my java program is saved in D drive javap
folder name as Simple)

ex: javac –d . Simple.java

The -d switch specifies the destination where to put the generated class file.

run command: java packagename.programname

ex: java mypack.Simple

The -d is a switch that tells the compiler where to put the class file i.e. it
represents destination. The . represents the current folder.

Types of Packages

Packages are divided into two categories:

1. Built-in Packages (packages from the Java API)


2. User-defined Packages (create your own packages)

1. Built-in Packages

The Java API is a library of predefined classes that are free to use, included in
the Java Development Environment.

The library contains components for managing input, database programming,


and much much more.

1) java.lang: Contains language support classes(e.g classed which defines


primitive data types, math operations). This package is automatically imported.

2) java.io: Contains classed for supporting input / output operations.

3) java.util: Contains utility classes which implement data structures like Linked
List, Dictionary and support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.

5) java.awt: Contain classes for implementing the components for graphical


user interfaces (like button , ;menus etc).

6) java.net: Contain classes for supporting networking operations.

2. User-defined packages (Create your own packages)

These are the packages that are defined by the user. First we create a directory
myPackage (name should be same as the name of the package). Then create the
MyClass inside the directory with the first statement being the package names.

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.

Example of package that import the packagename.*

//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();

} }

Compilation

Step1) javac –d . A.java

Step 2) javac –d . B .java

Run commnd:

Java mypack.B

Output: hello

2) Using packagename.classname
If you import package.classname then only declared class of this package will
be accessible.
Example of package by import package.classname

//save by A.java

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();

Output:Hello

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.
Example of package by import fully qualified name

//save by A.java

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();

Output: Hello

You might also like