0% found this document useful (0 votes)
14 views

JAVA Unit 2

Uploaded by

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

JAVA Unit 2

Uploaded by

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

UNIT II

Inheritance – Inheritance hierarchies super and sub classes, super keyword, preventing
inheritance: final classes and methods, the Object class and its methods. Polymorphism- dynamic
binding, static binding, abstract classes and methods. Interfaces – Interfaces vs. Abstract classes,
defining an interface, Multiple Inheritance through interface, extending interface. Packages-
Defining, Creating and Accessing a Package, Understanding CLASSPATH, importing packages.

Inheritance (IS-A) Definition:


Inheritance is the process by which one object acquires the properties of another object.
➢ Using inheritance, we can create a general class that defines characteristics common to a set of
related items.
➢ This class can then be inherited by other, more specific classes, each adding those things that
are unique to it.
Super class / Base class / Parent class
The class from which a subclass is derived is called the superclass.
Subclass / Derived class / Extended class / Child class
A class that is derived from another class is called a subclass.
A subclass inherits state(variables) and behavior (method) from all of its ancestors.

Note:
In the Java programming language, each class is allowed to have one direct super class, and each
super class has the potential for an unlimited number of subclasses.

Use inheritance in java


For Method Overriding (so runtime polymorphism can be achieved).
For Code Reusability

Class: A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created.
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.
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.
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 Java 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.

Types of inheritance in java


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.
We will learn about interfaces later.
Single Inheritance Multilevel Inheritance
class Animal class A{
{ void eat(){System.out.println("eating...");}
void eat() }
{
System.out.println("eating..."); class B extends A{
} void bark(){System.out.println("barking...");}
} }
class Dog extends Animal
{ class C extends B{
void bark() void weep()
{ {System.out.println("weeping...");}
System.out.println("barking..."); }
}
} class Test{
class TestInheritance public static void main(String args[]){
{ C d=new C();
public static void main(String args[]) d.weep();
{ d.bark();
Dog d=new Dog(); d.eat();
d.bark(); }}
d.eat();
}
}
Hierarchical Inheritance multiple Inheritance not supports in java
class A{ class A{
void eat(){System.out.println("eating...");} void msg(){System.out.println("Hello");}
} }
class B extends A{ class B{
void bark(){System.out.println("barking...");} void msg(){System.out.println("Welcome");}
} }
class C extends A{ class C extends A,B{//suppose if it were
void meow()
{System.out.println("meowing...");} public static void main(String args[]){
} C obj=new C();
class TestInheritance3{ obj.msg();//Now which msg() method would
public static void main(String args[]){ be invoked?
C d=new C(); }
d.meow(); }
d.eat();
//d.bark();//C.T.Error
}}

Method Overriding
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void eat()
{
System.out.println("barking...");
}
}
class TestInheritance
{
public static void main(String args[])
{
Dog d=new Dog();
d.eat();
Animal a=new Animal();
a.eat();
}
}
Super Keyword
The super keyword in Java is a reference variable which is used to refer immediate parent class
object.

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 can be 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();
}}

2. super can be used to invoke immediate parent class method.


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

3. super() can be used to invoke immediate 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();
}
}
Polymorphism

polymorphism is a concept of object-oriented programming that allows us to perform a single


action in different forms. In this section, we will discuss only the dynamic polymorphism in
Java.

The word polymorphism is a combination of two words i.e. ploy and morphs. The word poly
means many and morphs means different forms. In short, a mechanism by which we can
perform a single action in different ways.

Example.

A person in a shop is a customer, in an office, he is an employee, in the home he is husband/


father/son, in a party he is guest. So, the same person possesses different roles in different places.
It is called polymorphism.

Types of Polymorphism

There are two types of polymorphism in Java:

1. Compile time polymorphism (static polymorphism)


2. Run time polymorphism (dynamic polymorphism / dynamic method dispatch / virtual method
invocation)

1. Static polymorphism (or compile-time polymorphism) A Superclass Variable Can


Reference a Subclass Object.

a) Java achieves compile time polymorphism using Method Overloading.


b) In this, method resolution will happen at compile-time.
c) In this, compiler looks only at the reference type (not at the object type) and determines which
Overloaded method to call.
Polymorphism in Java, like most other OOP programming languages, allows for the inclusion of
several methods within a single class. Although the methods have the same name, the parameters
differ. The static polymorphism is represented by this. This polymorphism is achieved through
method overloading and is resolved during the compiler time. There are three conditions by
which the parameter sets must differ:

 The number of parameters should be varied.


 Different parameter types should be used.

The parameters are in a different sequence. If one method accepts a string and a long while the
other accepts a long and a string, for example. This form of order, on the other hand, makes it
tough for the API to grasp.

Every method has a different signature due to the differences in parameters. The Java compiler
knows which method is invoked.
Example of static polymorphism
One of the ways by which Java supports static polymorphism is method overloading. An
example showing the case of method overloading in static polymorphism is shown below:

Example:
class SimpleCalculator
{
int add(int a, int b)
{
return a+b;
}

int add(int a, int b, int c)


{
return a+b+c;
}
}

public class Demo


{
public static void main(String args[])
{
SimpleCalculator obj = new SimpleCalculator();
System.out.println(obj.add(25, 25));
System.out.println(obj.add(25, 25, 30));
}
}

Output of the program


50
80
2. Dynamic Polymorphism (or run time polymorphism in Java)

1) Java achieves run time polymorphism using Method Overriding.


2) In this,method resolution will happen at run time based on actual object.
3) Dynamic method dispatch is the mechanism by which a call to an overridden method is
resolved at run time, rather than compile time.
4) When a method is overridden, the child version of the method always executes at runtime.

The compiler does not determine the method to be executed in this type of polymorphism in
Java. The process is carried out at runtime by the Java Virtual Machine (JVM). When a call to an
overridden process is resolved at run time, it is referred to as dynamic polymorphism. The
overridden method is called by a superclass's reference variable. While the methods implemented
by both the subclass and the superclass have the same name, they provide separate functionality.

Dynamic polymorphism is a process or mechanism in which a call to an overridden method is


to resolve at runtime rather than compile-time. It is also known as runtime
polymorphism or dynamic method dispatch. We can achieve dynamic polymorphism by using
the method overriding.

In this process, an overridden method is called through a reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the reference
variable.

Properties of Dynamic Polymorphism


o It decides which method is to execute at runtime.
o It can be achieved through dynamic binding.
o It happens between different classes.
o It is required where a subclass object is assigned to a super-class object for dynamic
polymorphism.
o Inheritance involved in dynamic polymorphism.

Method Overriding

It provides a specific implementation to a method that is already present in the parent class. it is
used to achieve run-time polymorphism. Remember that, it is not possible to override
the static method. Hence, we cannot override the main() method also because it is a static
method.

Rules for Method Overriding


o The name of the method must be the same as the name of the parent class method.
o The number of parameters and the types of parameters must be the same as in the parent
class.
o There must exist an IS-A relationship (inheritance).

We call an overridden method through a reference of the parent class. The type of object decides
which method is to be executed and it is decided by the JVM at runtime.

Example of Dynamic Polymorphism

In the following example, we have created two classes named Sample and Demo. The Sample
class is a parent class and the Demo class is a child or derived class. The child class is
overriding the dispaly() method of the parent class.

We have assigned the child class object to the parent class reference. So, in order to determine
which method would be called, the type of the object would be decided by the JVM at run-time.
It is the type of object that determines which version of the method would be called (not the type
of reference).

class Sample
{
//method of the parent class
public void display()
{
System.out.println("Overridden Method");
}
}
//derived or child class
public class Demo extends Sample
{
//method of child class
public void display()
{
System.out.println("Overriding Method");
}
public static void main(String args[])
{
//assigning a child class object to parent class reference
Sample obj = new Demo();
//invoking display() method
obj.display();
}
}
final keyword: Three uses with final keyword: 2 & 3 are used with
Inheritance
1. To define constants
2. To prevent Method Overriding
3. To prevent Inheritance

To Prevent Method Overriding


By using final, we can prevent a method from being overridden. Methods declared as final
cannot be overridden.

class A {
final void meth() {
System.out.println("This is a final method.");
}
}
class B extends A
{
void meth() { // ERROR! Can't override.
System.out.println("Illegal!");
}
}
Because meth( ) is declared as final, it cannot be overridden in B. If we attempt to do so, a
compile-time error will result.
To Prevent Inheritance
To prevent a class from being inherited, declare the class as final. Declaring a class as final
implicitly declares all of its methods as final, too.
final class A
{
//...
}
// The following class is illegal.
class B extends A
{
// ERROR! Can't subclass A
//...
}

Abstract class //absract means partially implemented


An abstract class is a class that cannot be instantiated. An abstract class contains one or more
abstract methods.
Note: not possible to create object to abstract class
abstract class Figure {
public static void main(String args[])
{
Figure f=new Figure(); //compile time error
}
}

Abstract method // absract means partially completed


Abstract method is a method which do not contain it’s body. In other words, abstract method is a
method without any implementation.

Abstract method syntax:


abstract type name(parameter-list);

➢ Abstract methods are sometimes referred to as subclasser responsibility, because they


have no implementation specified in the superclass. So, subclass must override them.
➢ It is not possible to declare abstract constructors or abstract static methods.
➢ Any subclass of an abstract class must either implement all of the abstract methods in
the superclass, or be declared abstract itself.

Example:
Write a Java program to demonstrate abstract methods and abstract classes.
abstract class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a; dim2 = b;
}
// area is now an abstract method
abstract double area(); //PARTIALLY COMPLETED
}
class Rectangle extends Figure {
Rectangle(double a, double b)
{
super(a, b);
}
// override area for rectangle
double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure {
Triangle(double a, double b)
{
super(a, b);
}
// override area for right triangle
double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
class AbstractAreas {
public static void main(String args[]) {
// Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref; // this is OK, no object is created
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
}
}

Interfaces
Interfaces are like a 100-percent abstract superclass.
An interface is a contract.
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. There can be only abstract methods
in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance
in Java.

In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.

Java Interface also represents the IS-A relationship.


Why use Java interface?
There are mainly three reasons to use interface. They are given below.
1. It is used to achieve abstraction.
2. By interface, we can support the functionality of multiple inheritance.
3. It can be used to achieve loose coupling.
Definition: An interface is a reference type, similar to a class, that can contain only constants,
method signatures, default methods, static methods.
➢ Using interface, we can specify what a class must do, but not how it does it.
➢ Method bodies exist only for default methods and static methods.
➢ Interfaces cannot be instantiated—they can only be implemented by classes or extended by
other interfaces.
➢ Using interfaces, Java achieves the run time polymorphism - “one interface, multiple
methods” aspect of polymorphism.
Defining an Interface
access interface name {
// constants 1. access can be only default or
type final-varname = value; public.
//abstract methods
2. Variables defines inside an
return-type method-name(parameter-list); interface are implicitly public, final
//default methods and static, they must also be
default type method-name(parameter-list) initialized.
{
//body 3. All methods and variables are
} implicitly public.
//static methods Example:
static type method-name(parameter-list) public interface IntStack
{ {
//body void push(int n); int pop();
} }
}
Implementing Interfaces
Once an interface has been defined, one or more classes can implement that interface.
implements
class classname [extends superclass] [implements interface [,interface...]]
{
// class-body
}
Note: When we implement an interface method, it must be declared as public.

Example:
public interface IntStack
{
void push(int n); int pop();
}
class FixedStack implements IntStack
{
public void push(int n) { } public int pop() { }
}
Interfaces properties
1) Interfaces are implicitly abstract.
2) All interface methods are implicitly public and abstract.
3) All variables defined in an interface must be public, static, and final
4) Because interface methods are abstract, they cannot be marked final.
5) An interface can extend one or more other interfaces.
6) An interface can’t extend anything except another interface.
7) An interface cannot implement another interface or class.
8) An interface must be declared with the keyword interface.
9) Interface types can be used polymorphically .

Extending Interfaces
One interface can inherit another by use of the keyword extends. The syntax is the
same as for inheriting classes.
When a class implements an interface that inherits another interface, it must
provide implementations for all methods required by the interface inheritance
chain.

// One interface can extend another.


interface A {
void meth1(); void meth2();
}

// B now includes meth1() and meth2() -- it adds meth3().


interface B extends A {
void meth3();
}

// This class must implement all of A and B


class MyClass implements B {
public void meth1() {
System.out.println("Implement meth1().");
}
JAVA UNIT - III Page 28
public void meth2() {
System.out.println("Implement meth2().");
}
public void meth3() {
System.out.println("Implement meth3().");
}
}
class IFExtend {
public static void main(String arg[]) {
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}

Multiple Inheritance through interface


Multiple inheritance is not supported in the case of class because of ambiguity. However, it is
supported in case of an interface because there is no ambiguity. It is because its implementation
is provided by the implementation class.

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();
}
}
Nested Interface in Java An interface can have another interface which is known as a nested
interface.
Points to remember for nested interfaces
There are given some points that should be remembered by the java programmer.
1. The nested interface must be public if it is declared inside the interface, but it can have
any access modifier if declared within the class.
2. Nested interfaces are declared static
Ex:
interface Showable{
void show();
interface Message{
void msg();
}
}
class TestNestedInterface1 implements Showable.Message{
public void msg(){System.out.println("Hello nested interface");}

public static void main(String args[]){


Showable.Message message=new TestNestedInterface1();//upcasting here
message.msg();
}
}

Ex 1:
interface Printable{
void print();
}
interface Showable{
void print();
}

class TestInterface3 implements Printable, Showable


{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
TestInterface3 obj = new TestInterface3();
obj.print();
}
}

Ex 2:
File: TestInterface1.java

//Interface declaration: by first user


interface Drawable{
void draw();
}

//Implementation: by second user


class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}

class Circle implements Drawable{


public void draw(){System.out.println("drawing circle");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();
d.draw();
}}

Output:
drawing circle

Ex 3:
File: TestInterface2.java

interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest(){return 9.15f;}
}
class PNB implements Bank{
public float rateOfInterest(){return 9.7f;}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}}
Abstract class vs interface
Abstract class contains abstract and non- Interfaces do not contain non-abstract methods
abstract methods. but it contains only abstract methods
The abstract keyword is used to The interface keyword is used to
declare abstract class. declare interface.

Abstract class doesn't support Interface supports multiple


multiple inheritance. inheritance.

Abstract methods contains instance variables and Interfaces do not contain instance variables, it
constants. contains only constants.
Abstract methods needs to be declared as abstract All methods are implicitly public and abstract.
explicitly.
An abstract class can be extended An interface can be implemented using
using keyword "extends". keyword "implements".

Abstract class can extends another class, not An interface can extends another interfaces only,
interfaces not classes
An abstract class can implement an interface An interface cannot implement another interface or
class.
Ex: Ex:
abstract class A{ } interface Bounceable

Packages
A package is a grouping of related classes and interfaces.
Benefits of packages:
Packages provides -

✓ We can allow types within the package to have unrestricted access to one another yet still
a) access protection

restrict access for types outside the package.

✓ The names of one package types won’t conflict with the types in other packages.
b) Name space management.

c) Two different programmers can easily determine the types defined in the package are related.

Defining / Creating a Package


To create a package, we choose a name for the package and put a package statement with that
name at the top of every source file.

General form of a package statement:

✓ The package statement (for example, package graphics;) must be the first line in the source
package pkg; -> Here, pkg is the name of the package.

✓ There can be only one package statement in each source file, and it applies to all types in the
file.

✓ Java uses file system directories to store packages.


file.

✓ Ex: package MyPackage;


➢ the .class files for any classes that are part of MyPackage must be stored in a directory called
MyPackage.

Multilevel Packages
We can create a hierarchy of packages. To do so, simply separate each package name from the
one above it by use of a period.

The general form of a multileveled package statement is shown here:


package pkg1[.pkg2[.pkg3]];
Ex: package java.lang.system;
This needs to be stored in java\lang\system directory in windows environment.

Package categories
Two forms:
Built-in package:
➢ All of the standard Java classes included with Java are stored in a package called java.
➢ The basic language functions are stored in a package inside of the java package called
java.lang.

User-defined package:
User defined packages are the packages defined by the programmers specific to their
application.
Ex: package edu.cbit.example;
Access Protection in Java using Packages
In addition to the access modifiers (private,public,protected and default), packages will add
another dimension to access control.
Java addresses four categories of visibility for class members:
1. Subclasses in the same package
2. Non-subclasses in the same package
3. Subclasses in different packages
4. Classes that are neither in the same package nor subclasses

private No Modifier Protected Public


(default)
Same class Yes Yes Yes Yes
Same package No Yes Yes Yes
subclass
Same package No Yes Yes Yes
non-subclass
Different No No Yes Yes
package
subclass
Different No No No Yes
package non-
subclass

Simple example of java package


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

package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to compile java package

javac -d directory javafilename


For example: javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. If you want to keep
the package within the same directory, you can use . (dot).

How to run java package program


You need to use fully qualified name e.g. mypack.Simple etc to run the class.
java mypack.Simple

To Compile: javac -d . Simple.java


To Run: java mypack.Simple
Output:Welcome to package
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.

How to access package from another package?


There are three ways to access the package from outside the package.
 import package.*;
 import package.classname;
 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();
}
}

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

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

CLASSPATH
The CLASSPATH refers to the path on your file system where your .class files are saved, and
the classpath is defined by the CLASSPATH environment variable.

The CLASSPATH environment variable specifies the directories where you want the compiler
and the JVM to search for bytecode.

Finding Packages
How does the Java run-time system know where to look for packages that we create?
1. First, by default, the Java run-time system uses the current working directory as its starting
point. Thus, if our package is in a subdirectory of the current directory, it will be found.
2. We can specify a directory path or paths by setting the CLASSPATH environmental variable.
3. we can use the -classpath option with java and javac to specify the path to your classes.
Using the - classpath flag overrides the CLASSPATH environment variable.

You might also like