You are on page 1of 21

SRCMBMM SANCHALIT SMT K.

S KAPASHI BCA
COLLEGE,PALITANA
JAVA UNIT-3

 Inheritance

- The class which inherits the properties of other is known as subclass (derived
class, child class) and the class whose properties are inherited is known as
superclass (base class, parent class).
- Inheritance can be defined as the procedure or mechanism of acquiring all the
properties and behavior of one class to another, i.e., acquiring the properties and
behavior of child class from the parent class. This concept was built to achieve
the advantage of creating a new class that gets built upon an already existing
class(es). It is mainly used for code reusability within a Java program.
- Moreover, a hierarchical order of management of information can also be done
using this concept. Here two types of classes build relationships with each other
which are a base class and derived class.
- The class that gets inherited taking the properties of another class is the subclass
or derived class or child class. Again, the class whose properties get inherited is
the superclass or base class or parent class. The keyword extends used to inherit
the properties of the base class to derived class.

 Extends Keyword

extends is the keyword used to inherit the properties of a class. Following is the syntax of
extends keyword.

Syntax

class Super {
.....
.....
}
class Sub extends Super {
.....
.....

PREPARED BY: VEEDHEE AMBALIYA PAGE 1


SRCMBMM SANCHALIT SMT K.S KAPASHI BCA
COLLEGE,PALITANA
JAVA UNIT-3

Example:-

class employee {
intwt = 8;
}

class clerk extends employee {


intwt = 10; //work time
void display() {
System.out.println(super.wt); //will print work time of
clerk
}

public static void main(String args[]) {


clerk c = new clerk();
c.display();
}
}

 The super keyword

Super is a keyword of Java which refers to the immediate parent of a class and is used inside
the subclass method definition for calling a method defined in the superclass. A superclass
having methods as private cannot be called. Only the methods which are public and protected
can be called by the keyword super. It is also used by class constructors to invoke
constructors of its parent class.

Syntax:-

super.<method-name>();

 Super variables refer to the variable of a variable of the parent class.


 Super() invokes the constructor of immediate parent class.
 Super refers to the method of the parent class.

Example:-

class Superclass {
int age;

Superclass(int age) {
this.age = age;
}

public void getAge() {

PREPARED BY: VEEDHEE AMBALIYA PAGE 2


SRCMBMM SANCHALIT SMT K.S KAPASHI BCA
COLLEGE,PALITANA
JAVA UNIT-3

System.out.println("The value of the variable named age in


super class is: " +age);
}
}

public class Subclass extends Superclass {


Subclass(int age) {
super(age);
}

public static void main(String argd[]) {


Subclass s = new Subclass(24);
s.getAge();
}
}

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.

publicclassAnimal{
}

publicclassMammalextendsAnimal{
}

publicclassReptileextendsAnimal{
}

publicclassDogextendsMammal{
}

Now, based on the above example, in Object-Oriented terms, the following are true −

 Animal is the superclass of Mammal class.


 Animal is the superclass of Reptile class.
 Mammal and Reptile are subclasses 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

PREPARED BY: VEEDHEE AMBALIYA PAGE 3


SRCMBMM SANCHALIT SMT K.S KAPASHI BCA
COLLEGE,PALITANA
JAVA UNIT-3

With the 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.

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 look into an example −

Example

publicclassVehicle{}
publicclassSpeed{}

publicclassVanextendsVehicle{
privateSpeedsp;
}

 Types of Inheritance

PREPARED BY: VEEDHEE AMBALIYA PAGE 4


SRCMBMM SANCHALIT SMT K.S KAPASHI BCA
COLLEGE,PALITANA
JAVA UNIT-3

 Single inheritance:-

When a single class gets derived from its base class, then this type of inheritance is termed
as single inheritance. The figure drawn above has class A as the base class, and class B gets
derived from that base class.

class Teacher {
void teach() {
System.out.println("Teaching subjects");
}
}
class Students extends Teacher {
void listen() {
System.out.println("Listening to teacher");
}
}
classCheckForInheritance {
public static void main(String args[]) {
Students s1 = new Students();
s1.teach();
s1.listen();
}
}

 Multi-level Inheritance

In this type of inheritance, a derived class gets created from another derived class and can
have any number of levels.

Example:-

class Teacher {
void teach() {
System.out.println("Teaching subject");
}
}
class Student extends Teacher {
void listen() {
System.out.println("Listening");
}
}
classhomeTution extends Student {
void explains() {
System.out.println("Does homework");
}
}
classCheckForInheritance {

PREPARED BY: VEEDHEE AMBALIYA PAGE 5


SRCMBMM SANCHALIT SMT K.S KAPASHI BCA
COLLEGE,PALITANA
JAVA UNIT-3

public static void main(String argu[]) {


homeTution h = new himeTution();
h.explains();
d.teach();
d.listen();
}
}

 Hierarchical Inheritance

In this type of inheritance, there are more than one derived classes which get created from
one single base class.

Example:-

class Teacher {
void teach() {
System.out.println("Teaching subject");
}
}
class Student extends Teacher {
void listen() {
System.out.println("Listening");
}
}
class Principal extends Teacher {
void evaluate() {
System.out.println("Evaluating");
}
}
classCheckForInheritance {
public static void main(String argu[]) {
Principal p = new Principal();
p.evaluate();
p.teach();
// p.listen(); will produce an error
}
}

 Method Overriding

Declaring a method in the subclass which already exists there in the parent class is known as
method overriding. When a class is inheriting a method from a superclass of its own, then
there is an option of overriding the method provided it is not declared as final. The
advantage of using overriding is the ability to classify a behavior that's specific to the child
class, and the child class can implement a parent class method based on its necessity.

PREPARED BY: VEEDHEE AMBALIYA PAGE 6


SRCMBMM SANCHALIT SMT K.S KAPASHI BCA
COLLEGE,PALITANA
JAVA UNIT-3

There are certain rules that a programmer should follow to implement overriding. These are:

 In Java, a method can only be written in the child class and not in same class.
 Argument list should be the same as that of the overridden method of that class.
 Instance methods can also be overridden if they are inherited by the child class.
 A constructor cannot be overridden.
 Final - declared methods cannot be overridden.
 Any method that is static cannot be used to override.
 The return type must have to be the same, or a subtype of the return type declared in
the original overridden method in the parent class.
 If a method cannot be inherited, then it cannot be overridden.
 A child class within the same package as the instance's parent class can override any
parent class method that is not declared private or final.
 A child class in a different package can only override the non-final methods declared
as public or protected.

Example:-

class college {
public void move() {
System.out.println("College is open");
}
}
classuniv extends college {
public void move() {
System.out.println("University is open too");
}
}
public class stud {
public static void main(String args[]) {
college a = new college();
college b = new univ();
a.move();
b.move();
}
}
Example:-2

class parent {
public void work() {
System.out.println("Parent is under retirement from work.");
}
}
class child extends parent {
public void work() {
System.out.println("Child has a job");
System.out.println(" He is doing it well");
}

PREPARED BY: VEEDHEE AMBALIYA PAGE 7


SRCMBMM SANCHALIT SMT K.S KAPASHI BCA
COLLEGE,PALITANA
JAVA UNIT-3

public static void main(String argu[]) {


child c1 = new child();
c1.work();
}
}

 Polymorphism
 Static Polymorphism
 Dynamic Polymorphism.

Polymorphism is another special feature of object-oriented programming (OOPs). The


approach which lies beneath this concept is "single interface with multiple implementations."
It offers a single interface for controlling access to a general class of actions.

Polymorphism can be achieved in two of the following ways:

 Method Overloading(Compile time Polymorphism)


 Method Overriding(Run time Polymorphism)

 Abstract classes

A class which contains the abstract keyword in its declaration is known as abstract class.

 Abstract classes may or may not contain abstract methods, i.e., methods without body
( public void get(); )
 But, if a class has at least one abstract method, then the class must be declared
abstract.
 If a class is declared abstract, it cannot be instantiated.
 To use an abstract class, you have to inherit it from another class, provide
implementations to the abstract methods in it.
 If you inherit an abstract class, you have to provide implementations to all the abstract
methods in it.

PREPARED BY: VEEDHEE AMBALIYA PAGE 8


SRCMBMM SANCHALIT SMT K.S KAPASHI BCA
COLLEGE,PALITANA
JAVA UNIT-3

Example:-

abstract class cycle {


abstract void work();
}

classHeroCycle extends cycle {


void work() {
System.out.println("Selling good");
}

public static void main(String argu[]) {


cycle o = new HeroCycle();
o.work();
System.out.println("Code executed");
}

}
 Abstract method
When a programmer wants any class having a specific method but also want the actual
execution of that method to be resolute by its child classes, the methods can be declared in
the base class in the form of abstract methods.

 The keyword abstract is used for declaring abstract method


 The abstract keyword needs to be implemented before the name of method
 Abstract method does not contain any method body
 If there are no curly braces given, there should have to be semicolon put at the end of
the abstract method

public abstract class professor {


private String str;
private float sal;
privateintregnNo;
public abstract double salaryCompute();
// abstract metho body here
}

 Interfaces
An interface is a reference type in Java. It is similar to class. It is a collection of abstract
methods. A class implements an interface, thereby inheriting the abstract methods of the
interface.

Writing an interface is similar to writing a class. But a class describes the attributes and
behaviors of an object. And an interface contains behaviors that a class implements.

PREPARED BY: VEEDHEE AMBALIYA PAGE 9


SRCMBMM SANCHALIT SMT K.S KAPASHI BCA
COLLEGE,PALITANA
JAVA UNIT-3

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

Use:-

 For achieving full data abstraction


 Using Interface, you can use the concept of multiple inheritances
 Interfaces can also be used to achieve loose coupling

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

 You cannot instantiate an interface.


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

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

 You cannot instantiate an interface.


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

Declaring Interfaces

The interface keyword is used to declare an interface. Here is a simple example to declare an
interface −

Example
/* File name : NameOfInterface.java */
importjava.lang.*;
// Any number of import statements

publicinterfaceNameOfInterface{
// Any number of final, static fields
// Any number of abstract method declarations\
}

Interfaces have the following properties −

PREPARED BY: VEEDHEE AMBALIYA PAGE 10


SRCMBMM SANCHALIT SMT K.S KAPASHI BCA
COLLEGE,PALITANA
JAVA UNIT-3

 An interface is implicitly abstract. You do not need to use the abstract keyword while
declaring an interface.
 Each method in an interface is also implicitly abstract, so the abstract keyword is not
needed.
 Methods in an interface are implicitly public.

Example
/* File name : Animal.java */
interfaceAnimal{
publicvoid eat();
publicvoid travel();
}

Implementing Interfaces

When a class implements an interface, you can think of the class as signing a contract,
agreeing to perform the specific behaviors of the interface. If a class does not perform all the
behaviors of the interface, the class must declare itself as abstract.

When implementation interfaces, there are several rules −

 A class can implement more than one interface at a time.


 A class can extend only one class, but implement many interfaces.
 An interface can extend another interface, in a similar way as a class can extend
another class.

A class uses the implements keyword to implement an interface. The implements keyword
appears in the class declaration following the extends portion of the declaration.

Example
/* File name : MammalInt.java */
publicclassMammalIntimplementsAnimal{

publicvoid eat(){
System.out.println("Mammal eats");
}

publicvoid travel(){
System.out.println("Mammal travels");
}

publicintnoOfLegs(){
return0;
}

publicstaticvoid main(Stringargs[]){
MammalInt m =newMammalInt();

PREPARED BY: VEEDHEE AMBALIYA PAGE 11


SRCMBMM SANCHALIT SMT K.S KAPASHI BCA
COLLEGE,PALITANA
JAVA UNIT-3

m.eat();
m.travel();
}
}

Extending Interfaces

An interface can extend another interface in the same way that a class can extend another
class. The extends keyword is used to extend an interface, and the child interface inherits the
methods of the parent interface.

The following Sports interface is extended by Hockey and Football interfaces.

Example
// Filename: Sports.java
publicinterfaceSports{
publicvoidsetHomeTeam(String name);
publicvoidsetVisitingTeam(String name);
}

// Filename: Football.java
publicinterfaceFootballextendsSports{
publicvoidhomeTeamScored(int points);
publicvoidvisitingTeamScored(int points);
publicvoidendOfQuarter(int quarter);
}

// Filename: Hockey.java
publicinterfaceHockeyextendsSports{
publicvoidhomeGoalScored();
publicvoidvisitingGoalScored();
publicvoidendOfPeriod(int period);
publicvoidovertimePeriod(intot);
}

Extending Multiple Interfaces

A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces
are not classes, however, and an interface can extend more than one parent interface.The
extends keyword is used once, and the parent interfaces are declared in a comma-separated
list.

For example, if the Hockey interface extended both Sports and Event, it would be declared as

Example
publicinterfaceHockeyextendsSports,Event

PREPARED BY: VEEDHEE AMBALIYA PAGE 12


SRCMBMM SANCHALIT SMT K.S KAPASHI BCA
COLLEGE,PALITANA
JAVA UNIT-3

 Introduction to Packages
A package is a mechanism to group the similar type of classes, interfaces and sub-packages
and provide access control. It organizes classes into single unit.
In Java already many predefined packages are available, used while programming.
For example: java.lang, java.io, java.util etc.

Advantages of Packages

 Packages provide code reusability, because a package has group of classes.


 It helps in resolving naming collision when multiple packages have classes with the
same name.
 Package also provides the hiding of class facility. Thus other programs cannot use the
classes from hidden package.
 Access limitation can be applied with the help of packages.
 One package can be defined in another package.

 Types of Packages
There are two types of packages available in Java.

1. Built-in packages
Built-in packages are already defined in java API. For example: java.util, java.io, java,lang,
java.awt, java.applet, java.net, etc.
2. User defined packages
The package we create according to our need is called user defined package.

Creating a Package
We can create our own package by creating our own classes and interfaces together. The
package statement should be declared at the beginning of the program.
Syntax:

package <packagename>;
class ClassName
{
……..
……..
}

PREPARED BY: VEEDHEE AMBALIYA PAGE 13


SRCMBMM SANCHALIT SMT K.S KAPASHI BCA
COLLEGE,PALITANA
JAVA UNIT-3

Example: Creating a Package

// Demo.java
package p1;
class Demo
{
public void m1()
{
System.out.println("Method m1..");
}
}

How to compile?
Syntax: javac –d directory javafilename
For Example: javac –d . Demo.java

How to run?
To run: java p1.Demo

Example: Program to create and use a user defined ackage in Java.

// Vehicle.java
package vehicles;
interface Vehicle
{
public void run();
public void speed();
}

//Bike.java
package vehicles;
public class Bike implements Vehicle
{
public void run()
{
System.out.println("Bike is running.");
}
public void speed()
{
System.out.println("Speed of Bike: 50 Km/h");
}
public static void main(String args[])
{
Bike bike = new Bike();

PREPARED BY: VEEDHEE AMBALIYA PAGE 14


SRCMBMM SANCHALIT SMT K.S KAPASHI BCA
COLLEGE,PALITANA
JAVA UNIT-3

bike.run();
bike.speed();
}
}

Compile:
javac –d . Vehicle.java
javac –d . Bike.java

Run:
java vehicles.Bike

Output:
Bike is running
Speed of Bike: 50 Km/h

 The “import” keyword

The import keyword provides the access to other package classes and interfaces in current
packages. “import” keyword is used to import built-in and user defined packages in java
program.

 Interface

 Interface is similar to a class, but it contains only abstract methods.


 By default the variables declared in an interface are public, static and final.
 Interface is a mechanism to achieve full abstraction.
 An interface does not contain any constructor.

Syntax:

interface InterfaceName
{
public void method1();
public void method2();
<type> variableName = value;
}

PREPARED BY: VEEDHEE AMBALIYA PAGE 15


SRCMBMM SANCHALIT SMT K.S KAPASHI BCA
COLLEGE,PALITANA
JAVA UNIT-3

Example: Sample of an interface

interface Employee
{
static final Id = 101;
static final String name = “ABC”;
void show();
void getSalary(double salary);
}

 Extending interfaces
An interface has to extend another interface as it happens in class. It cannot implement another
interface.

Example: Sample program for extending interfaces

interface Base
{
public void display ();
}
interface Derive extends Base
{
public void show ();
}

 Implementing interfaces
 A class implements an interface. After that, class can perform the specific behavior on
an interface.
 The implements keyword is used by class to implement an interface.

Syntax:

class ClassName implements interfacename


{
// body of class
}

interface Results
{
final static float pi = 3.14f;
float areaOf(float l, float b);
}
class Rectangle implements Results
{
public float areaOf(float l, float b)

PREPARED BY: VEEDHEE AMBALIYA PAGE 16


SRCMBMM SANCHALIT SMT K.S KAPASHI BCA
COLLEGE,PALITANA
JAVA UNIT-3

{
return (l * b);
}
}
class Square implements Results
{
public float areaOf(float l, float b)
{
return (l * l);
}
}
class Circle implements Results
{
public float areaOf(float r, float b)
{
return (pi * r * r);
}
}
public class InterfaceDemo
{
public static void main(String args[])
{
Rectangle rect = new Rectangle();
Square square = new Square();
Circle circle = new Circle();
System.out.println("Area of Rectangle: "+rect.areaOf(20.3f, 28.7f));
System.out.println("Are of square: "+square.areaOf(10.0f, 10.0f));
System.out.println("Area of Circle: "+circle.areaOf(5.2f, 0));
}
}

Output:
Area of Rectangle: 582.61
Are of square: 100.0
Area of Circle: 84.905594

Example: Sample program to implements multiple inheritance

interface Vehicle
{
void run();
}
interface Bike extends Vehicle
{
void stop();
}
public class Demo implements Bike

PREPARED BY: VEEDHEE AMBALIYA PAGE 17


SRCMBMM SANCHALIT SMT K.S KAPASHI BCA
COLLEGE,PALITANA
JAVA UNIT-3

{
public void run()
{
System.out.println("Vehicle is running.");
}
public void stop()
{
System.out.println("Bike is stop.");
}
public static void main(String args[])
{
Demo obj = new Demo();
obj.run();
obj.stop();
}
}

Output:
Vehicle is running.
Bike is stop.

 Marker Interface
An interface which does not contain any fields and methods is known as marker or tag
interface. It is an empty interface.

For example Serializable, EventListener, MouseListner, Remote, Cloneable etc.

Example:
package java.util;
public interface EventListner
{
}

Differences between Abstract class and Interface

Abstract class Interface


It cannot support multiple inheritances. Interface supports multiple inheritances.
It contains both abstract and non abstract method. It contains only abstract method.
Abstract class is the partially implemented class. Interface is fully unimplemented class.
It cannot have main method and
It can have main method and constructor.
constructor.
It can have static, non-static, final, non-final
It contains only static and final variable.
variables.

PREPARED BY: VEEDHEE AMBALIYA PAGE 18


SRCMBMM SANCHALIT SMT K.S KAPASHI BCA
COLLEGE,PALITANA
JAVA UNIT-3

 Access Modifiers(Access Protection)

Access modifiers are simply a keyword in Java that provides accessibility of a class and its
member. They set the access level to methods, variable, classes and constructors.

 Types of access modifier

There are 4 types of access modifiers available in Java.

 public
 default
 protected
 private

 public

The member with public modifiers can be accessed by any classes. The public methods,
variables or class have the widest scope.

Example: Sample program for public access modifier

public static void main(String args[])


{
// code
}

 default
When we do not mention any access modifier, it is treated as default. It is accessible only within
same package.

Example: Sample program for default access modifier

int a = 25;
String str = "Java";
boolean m1()
{
return true;
}

PREPARED BY: VEEDHEE AMBALIYA PAGE 19


SRCMBMM SANCHALIT SMT K.S KAPASHI BCA
COLLEGE,PALITANA
JAVA UNIT-3

 protected
The protected modifier is used within same package. It lies between public and default access
modifier. It can be accessed outside the package but through inheritance only.
A class cannot be protected.

Example: Sample program for protected access modifier

class Employee
{
protected int id = 101;
protected String name = "Jack";
}
public class ProtectedDemo extends Employee
{
private String dept = "Networking";
public void display()
{
System.out.println("Employee Id : "+id);
System.out.println("Employee name : "+name);
System.out.println("Employee Department : "+dept);
}
public static void main(String args[])
{
ProtectedDemo pd = new ProtectedDemo();
pd.display();
}
}

Output:
Employee Id : 101
Employee name : Jack
Employee Department : Networking

 Private
The private methods, variables and constructor are not accessible to any other class. It is the most
restrictive access modifier. A class except a nested class cannot be private.

Example: Sample program for private access modifier

public class PrivateDemo


{
private int a = 101;
private String s = "TutorialRide";

PREPARED BY: VEEDHEE AMBALIYA PAGE 20


SRCMBMM SANCHALIT SMT K.S KAPASHI BCA
COLLEGE,PALITANA
JAVA UNIT-3

public void show()


{
System.out.println("Private int a = "+a+"\nString s = "+s);
}
public static void main(String args[])
{
PrivateDemo pd = new PrivateDemo();
pd.show();
System.out.println(pd.a+" "+pd.s);
}
}

Output:
Private int a = 101
String s = TutorialRide
101 TutorialRide

Table for Access Modifier

Access modifier In class In package Outside package by subclass Outside package

Public Yes Yes Yes No

protected Yes Yes Yes No

Default Yes Yes No No

Private Yes No No No

PREPARED BY: VEEDHEE AMBALIYA PAGE 21

You might also like