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

UNIT-II

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)
3 views

UNIT-II

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/ 26

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent

object.

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

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

Why use inheritance in java


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

Types of inheritance in java


When we talk about inheritance the most commonly used keyword would be extends and implements. These
words would determine whether one object IS-A type of another. By using these keywords we can make one object
acquire the properties of another object.

IS-A Relationship:

IS-A is a way of saying : This object is a type of that object. Let us see how the extends keyword is used to achieve
inheritance.

public class Animal{


}

public class Mammal extends Animal{


}

public class Reptile extends Animal{


}

public class Dog extends Mammal{


}

Now based on the above example, In Object Oriented terms following are true:

⮚ Animal is the superclass of Mammal class.

⮚ Animal is the superclass of Reptile class.

⮚ Mammal and Reptile are sub classes of Animal class.

⮚ Dog is the subclass of both Mammal and Animal classes.

Now if we consider the IS-A relationship we can say:

⮚ Mammal IS-A Animal

⮚ Reptile IS-A Animal

⮚ Dog IS-A Mammal

⮚ Hence : Dog IS-A Animal as well

With use of the extends keyword the subclasses will be able to inherit all the properties of the superclass except for
the private properties of the superclass.

We can assure that Mammal is actually an Animal with the use of the instance operator.

Example:
public class Dog extends Mammal{

public static void main(String args[]){

Animal a = new Animal();


Mammal m = new Mammal();
Dog d = new Dog();

System.out.println(m instanceof Animal);


System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}

This would produce following result:

true
true
true
Since we have a good understanding of the extends keyword let us look into how the implementskeyword is used
to get the IS-A relationship.
The implements keyword is used by classes by inherit from interfaces. Interfaces can never be extended by the
classes.

Example:

public interface Animal {}

public class Mammal implements Animal{


}

public class Dog extends Mammal{


}

The instanceof Keyword:

Let us use the instanceof operator to check determine whether Mammal is actually an Animal, and dog is actually
an Animal
interface Animal{}

class Mammal implements Animal{}

public class Dog extends Mammal{


public static void main(String args[]){

Mammal m = new Mammal();


Dog d = new Dog();
System.out.println(m instanceof Animal);
System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}

This would produce following result:

true
true
true

HAS-A relationship:

These relationships are mainly based on the usage. This determines whether a certain class HAS-A certain thing.
This relationship helps to reduce duplication of code as well as bugs.

Lets us look into an example:

public class Vehicle{}


public class Speed{}
public class Van extends Vehicle
{
private Speed sp;
}

This shows that class Van HAS-A Speed. By having a separate class for Speed we do not have to put the entire code
that belongs to speed inside the Van class., which makes it possible to reuse the Speed class in multiple
applications.

In Object Oriented feature the users do not need to bother about which object is doing the real work. To achieve
this, the Van class hides the implementation details from the users of the Van class. SO basically what happens is
the users would ask the Van class to do a certain action and the Vann class will either do the work by itself or ask
another class to perform the action.

A very important fact to remember is that Java only supports only single inheritance. This means that a class cannot
extend more than one class. Therefore following is illegal:

public class extends Animal, Mammal{}

However a class can implement one or more interfaces. This has made Java get rid of the impossibility of multiple
inheritance

1. POLYMORPHISM
Polymorphism literally means taking more than one form .polymorphism is a characteristic of being able to assign a
different behavior or value in a subclass,to something that was declared in a parent class.

Polymorphism means—One name many forms

Types of polymorphism:

⮚ Static polymorphism (method overloading)


⮚ Dynamic polymorphism

Dynamic polymorphism is a mechanism by which a call to am overridden function is resolved at run-time.

Dynamic method dispatch is important because this is how java implements run time polymorphism.

When an overridden method is called through a super class reference JVM determines which version of that
method is to be executed based on the type of object being referred at the time, the call occurs.

In other words, it is the type of object being referred to, determines which version of overridden method will be
executed.

Program to demonstrate dynamic method dispatch or dynamic polymorphism

class A
{
void show()
{
System.out.println("Inside class A");
}
}
class B extends A
{
void show()
{
System.out.println("Inside class B");
}

}
class C extends A
{
void show()
{
System.out.println("Inside class C");
}
}
class dynamicpoly
{
public static void main(String s[])
{
A a1=new A();
a1.show();
A a2;
B b1=new B();
a2=b1;
a2.show();
C c1=new C();
a2=c1;
a2.show();
c1.show();
}
}

2. “super” keyword

⮚ The super is a keyword defined in the java programming language. Keywords are basically reserved
words which have specific meaning relevant to a compiler in java programming language likewise the
super keyword indicates the following :

-- The super keyword in java programming language refers to the super class of the class where the
super keyword is currently being used.
-- The super keyword as a standalone statement is used to call the constructor of the super class in
the base class.

Programs for super keyword

class one
{
int i;
one(int i)
{
this.i=i;
}
}
class two extends one
{
int i;
two(int a,int b)
{
super(a);
i=b;
}
void show()
{
System.out.println("subclass var. = "+i);
System.out.println("super class var. = "+super.i);
}
}
class superdemo1
{
public static void main(String[] args)
{
two t = new two(10,20);
t.show();
}
}

class one
{
one()
{
System.out.println("one");
}
}
class two extends one
{
two()
{
System.out.println("two");
}
}
class superdemo
{
public static void main(String[] args)
{
two t = new two();
}
}

3. “this” keyword

The this keyword helps in removing the ambiguity of references and allows to refer to the current instance within
the running program.
-- key word this is used with variables as "this.variable" and specifies the number of member variable of this
instance of that class.

Program to demonstrate this keyword

class sample
{
int x;
sample()
{
this(55);
this.access();
}
sample(int x)
{
this.x=x;
}
void access()
{
System.out.println("x = "+x);
}
}
class thisdemo
{
public static void main(String[] args)
{
sample s = new sample();
}
}

4. “final” keyword

The keyword “final” means once created the property of that particular entity cannot be changed that is:
⮚ Final variables cannot be re-assigned with values
⮚ Final methods cannot be overridden
⮚ Final classes cannot be extended.

Program to show that Final variables cannot be re-assigned with values

class finalvariable
{
public static void main(String[] args)
{
int x=100;
final int y=200;
x=500;
y=800;
System.out.println(x+" "+y);

}
}

Output

Program to show that Final methods cannot be overridden


class A
{
final void display()
{
System.out.println("final method");
}
}
class B extends A
{
void display()
{
System.out.println("normal method");
}
}
class finalmethod
{
public static void main(String[] args)
{
B x = new B();
x.display();
}
}
Output

Program to show that Final classes cannot be extended

final class demo1


{
void display()
{
System.out.println("base class");
}
}
class demo2 extends demo1
{
void show()
{
System.out.println("derived class");
}
}
class finaldemo
{
public static void main(String args[])
{
demo2 d = new demo2();
d.display();
d.show();
}
}

Output
5. Abstract method and Abstract class
⮚ Abstraction is a process of hiding the implementation details and showing only functionality to the
user.
⮚ Another way, it shows only important things to the user and hides the internal details for example
sending sms, you just type the text and send the message. You don't know the internal processing
about the message delivery.
⮚ Abstraction lets you focus on what the object does instead of how it does it.

When to use abstract classes?

⮚ There are situations in which you will want to define a superclass that declares the structure of a
given abstraction without providing a complete implementation of every method.
⮚ That is, sometimes you will want to create a superclass that only defines a generalized form that will
be shared by all of its subclasses, leaving it to each subclass to fill in the details.
⮚ Such a class determines the nature of the methods that the subclasses must implement.

⮚ One way this situation can occur is when a superclass is unable to create a meaningful
implementation for a method.

There are two ways to achieve abstraction in java

⮚ Abstract class

⮚ Interface
o A class that is declared as abstract is known as abstract class. It needs to be extended and its method
implemented. It cannot be instantiated.
o A method that is declared as abstract and does not have implementation is known as abstract method.
o If there is any abstract method in the class then that class is known as abstract class

The abstract keyword is also used to declare a method as abstract. An abstract method consists of a method
signature, but no method body.

Abstract method would have no definition, and its signature is followed by a semicolon, not curly braces as follows:

abstract class Employee


{
String name;
int number;

abstract double computePay(); }


Program to demonstrate abstract class and abstract methods

abstract class car


{
int regno;
car(int r)
{
regno = r;
System.out.println(regno);
}

void opentank()
{
System.out.println("fill the tank");
}
abstract void steering();
abstract void breaking();
}
class maruti extends car
{
maruti(int r)
{
super(r);
}
void steering()
{
System.out.println("maruti car");
}
void breaking()
{
System.out.println("apply breaks to maruti");
}
}

class swift extends car


{
swift(int r)
{
super(r);
}
void steering()
{
System.out.println("swift car");
}

void breaking()
{
System.out.println("apply breaks to swift");
}
}
class drive
{
public static void main(String[] args)
{
maruti m = new maruti(100);
swift s = new swift(200);
car ref;
ref = m;
ref.opentank();
ref.steering();
ref.breaking();
ref = s;
ref.opentank();
ref.steering();
ref.breaking();

}
}

6. INTERFACE IN JAVA
Java doesn’t support multiple inheritance

⮚ Reason is, in java one sub class should have only one super class.

⮚ But in the case of multiple inheritance this rule is violated as in multiple inheritance we have one sub
class and more than one super classes.
⮚ Hence java does not directly support multiple inheritance but implements it using the interface
concept.
⮚ Consider the following figure to understand the problem that arises in case of multiple inheritance.

An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract
methods of the interface.

An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A
class describes the attributes and behaviors of an object. An interface contains behaviors that a class implements.

Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in
the class.

An interface is similar to a class in the following ways:

o An interface can contain any number of methods.


o An interface is written in a file with a .java extension, with the name of the interface matching the name of the
file.
o The bytecode of an interface appears in a .class file.

o Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that
matches the package name.

However, an interface is different from a class in several ways, including:

o You cannot instantiate an interface.


o An interface does not contain any constructors.
o All of the methods in an interface are abstract.
o An interface cannot contain instance fields. The only fields that can appear in an interface must be declared
both static and final.
o An interface is not extended by a class; it is implemented by a class.
o An interface can extend multiple interfaces.

Declaring Interfaces:

⮚ The interface keyword is used to declare an interface

⮚ implements keyword is used to write implementation classes for interface.

Syntax to declare interface is:

interface interface_name
{
Method declarations
}

Program to demonstrate Interface

interface aicte
{
void recognition();
}
interface EnggCollege
{
void syllabus();
void strength();
}
interface OU extends EnggCollege
{
void labs();
}
class A implements aicte, EnggCollege
{
public void recognition()
{
System.out.println("This college has been recognised by aicte");
}
public void syllabus()
{
System.out.println("Syllabus: 6 subjects for every sem");
}
public void strength()
{
System.out.println("Minimum strength of College must be 60");
}
}
class B implements aicte, OU
{
public void recognition()
{
System.out.println("This college has been recognised by aicte");
}
public void labs()
{
System.out.println("Labs facility is present in this college");
}
public void syllabus()
{
System.out.println("Syllabus: 6 subjects for every sem");
}
public void strength()
{
System.out.println("Minimum strength of College must be 60");
}
}
class interfacedemo
{
public static void main(String args[])
{
A a = new A();
B b = new B();
System.out.println("For class A:");
a.recognition();
a.syllabus();
a.strength();
System.out.println("For class B:");
b.recognition();
b.labs();
b.syllabus();
b.strength();
}
}

7. Interface Vs. Abstract class


8. Packages
o A java package is a group of similar types of classes, interfaces and sub-packages.
o Package in java can be categorized in two form, built-in package and user-defined package.

• Package names have a correspondence with the directory structure


• Packages Avoid name space collision. There can not be two classes with same name in a same Package
But two packages can have a class with same name.
• Exact Name of the class is identifed by its package structure.
<< Fully Qualified Name>>
Examples:
java.lang.String ; java.util.Arrays; java.io.BufferedReader ; java.util.Date

How To Create a Package

• Packages are mirrored through directory structure.

• To create a package, First we have to create a directory /directory structure that matches the package
hierarchy.

• Package structure should match the directory structure also.

• To make a class belongs to a particular package include the package statement as the first statement of
source file.

Examples:

Package ABC and IJK have classes with same name.

A class in ABC has name mypackage.mypackageA.ABC.A

A class in IJK has name mypackage.mypackageB.IJK.A

IMPORTING THE PACKAGE


• Import statement allows the importing of package

• Library packages are automatically imported irrespective of the location of compiling and executing
program

• JRE looks at two places for user created packages

(i) Under the current working directory

(ii) At the location specified by CLASSPATH

environment variable

• Most ideal location for compiling/executing a program is immediately above the package structure.

Defining a Package

To create a package is quite easy: simply include a package command as the first
statement in a Java source file. Any classes declared within that file will belong to the specified package. The
package statement defines a name space in which classes are stored. If you omit the package statement, the class
names are put into the default package, which has no name. (This is why you haven’t had to worry about packages
before now.) While the default package is fine for short, sample programs, it is inadequate for real applications.
Most of the time, you will define a package for your code.

This is the general form of the package statement:

package pkg;

Here, pkg is the name of the package. For example, the following statement creates a package called MyPackage.

package MyPackage;

Java uses file system directories to store packages. For example, the .class files for any classes you declare to be
part of MyPackage must be stored in a directory called MyPackage. Remember that case is significant, and the
directory name must match the package name exactly.

More than one file can include the same package statement. The package statement simply specifies to which
package the classes defined in a file belong. It does not exclude other classes in other files from being part of that
same package. Most real-world packages are spread across many files.
You 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]];

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.

Access Modifiers in java

There are two types of modifiers in java: access modifiers and non-access modifiers.

The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or class.

There are 4 types of java access modifiers:

1. private (accessible only within class.)


2. default (If you don't use any modifier, it is treated as default bydefault. The default modifier is accessible
only within package.)
3. protected (accessible within package and outside the package but through inheritance only. The protected
access modifier can be applied on the data member, method and constructor. It can't be applied on the
class )
4. public (accessible everywhere)

There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient etc. Here, we
will learn access modifiers.

Access modifiers work in java as shown in the following table:

Program to demonstrate Packages:


addition.java
package p1;
public class addition
{
int x,y,z;
addition(int a,int b)
{
x=a;
y=b;
}
void add()
{
z=x+y;
System.out.println("sum="+z);
}
}

subtraction.java

package p1;
public class subtraction
{
int x,y,z;
public subtraction(int a,int b)
{
x=a;
y=b;
}
public void sub()
{
z=x-y;
System.out.println("difference="+z);
}
}

multiplication.java
package p1;
public class multiplication
{
int x,y,z;
public multiplication(int a,int b)
{
x=a;
y=b;
}
public void multiply()
{
z=x*y;
System.out.println("product="+z);
}
}

packagedemo.java
import p1.addition;
import p1.subtraction;
import p1.multiplication;
public class packagedemo
{
public static void main(String args[])
{

addition a=new addition(10,20);


subtraction s=new subtraction(40,30);
multiplication m= new multiplication(5,6);
a.add();
s.sub();
m.multiply();
}
}

Output:

program to demonstrate access specifiers in packages:

A.java
package access;
public class A
{
int p=10;
private int q=20;
public int r=30;
protected int s=40;
}

B.java (same package sub class)


package access;
public class B extends A
{
public static void main(String args[])
{
B x=new B();
System.out.println(x.p);
System.out.println(x.q);
System.out.println(x.r);
System.out.println(x.s);
}
}

If System.out.println(x.q); is commented in the above program then


C.java (same package non-sub class)
package access;
public class C
{
public static void main(String args[])
{
A x=new A();
System.out.println(x.p);
System.out.println(x.q);
System.out.println(x.r);
System.out.println(x.s);
}
}

If System.out.println(x.q); is commented in the above program then

D.java (different package sub-class)


package access1;
import access.A;
public class D extends A
{
public static void main(String args[])
{
D y=new D();
System.out.println(y.p);
System.out.println(y.q);
System.out.println(y.r);
System.out.println(y.s);
}
}

If
System.out.println(y.p);
System.out.println(y.q); are commented in the above the program then:

E.java ( different package non-sub class)


package access1;
import access.A;
public class E
{
public static void main(String args[])
{
A y=new A();
System.out.println(y.p);
System.out.println(y.q);
System.out.println(y.r);
System.out.println(y.s);
}
}
If
System.out.println(y.p);
System.out.println(y.q);
System.out.println(y.s); are commented in the above program then

You might also like