Inheritance Unit I I I

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 45

CORE JAVA

Inheritance: Derived Class Objects, Inheritance and Access Control, Default


Base Class Constructors, this and super keywords.
Abstract Classes And Interfaces, Abstract Classes, Abstract Methods,
Interfaces, What Is An Interface? How Is An Interface Different From An
Abstract Class?, Multiple Inheritance, Default Implementation, Adding New
Functionality, Method Implementation, Classes V/s Interfaces, Defining An
Interface, Implementing Interfaces.
Packages: Creating Packages, Default Package, Importing Packages, Using A
Package.
Inheritance
Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviors of a parent object. It is an important part of OOPs
(Object Oriented programming system).
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.

Why use inheritance in java


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

For Code Reusability.


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

▪ In the terminology of Java, a class which is inherited is called a parent or


superclass, and the new class is called child or subclass.

Page ▪ 4
Inheritance
As displayed in the above figure, Programmer is the subclass and Employee
is the superclass. The relationship between the two classes is Programmer
IS-A Employee. It means that Programmer is a type of Employee.

Page ▪ 5
Inheritance 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);
}
}
Page ▪ 6
Single Inheritance
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();
Page ▪ 7
}}
Class A
{

}
Class B extends A
{

Page ▪ 8
Multilevel Inheritance

Page ▪ 9
Class A
{

}
Class B extends A
{

}
Class C extends B
{

Page ▪ 10
Hierarchical Inheritance

Page ▪ 11
Class A
{

}
Class B extends A
{

}
Class C extends A
{

Page ▪ 12
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.
❑ Usage of Java Method Overriding
Method overriding is used to provide the specific implementation
of a method which is already provided by its superclass.
Method overriding is used for runtime polymorphism.

❑ Rules for Java Method Overriding


The method must have the same name as in the parent class.
The method must have the same parameter as in the parent class.
There must be an IS-A relationship (inheritance).
Page ▪ 13
Class A
{
void demo()
{
}

}
Class B extends A
{
void demo()
{
}
}
Class C
{ P. s.v.m()
{ B obj=new B();
obj.demo();
}
Page ▪ 14

}
Method Overriding Example

Page ▪ 15
Base class constructor

Page ▪ 16
Abstract Class
A class which is declared with the abstract keyword is known as an
abstract class in Java. It can have abstract and non-abstract methods
(method with the body).
It needs to be extended and its method implemented. It cannot be
instantiated.
It can have constructors and static methods also.

Example:
abstract class A{}
❑ Abstract Methods in Java
A method which is declared as abstract and does not have implementation is
known as an abstract method.
abstract void printStatus(); //no method body and abstract
Page ▪ 17
Abstract Class(Contd.)
Example:
abstract class Bike
{
abstract void run();
}
class Vehicle extends Bike
{
void run()
{
System.out.println("running safely");
}
public static void main(String args[])
{
Bike obj = new Vehicle();
obj.run();
}
}
Page ▪ 18
Abstract Class(Contd.)
Example: class TestBank
abstract class Bank {
{ public static void main(String args[])
abstract int getRateOfInterest();
} {
class SBI extends Bank Bank b=new PNB();
{ int interest=b.getRateOfInterest();
int getRateOfInterest()
{return 7;} System.out.println("Rate of Interest is:
} "+interest+" %");
class PNB extends Bank }
{ }
int getRateOfInterest()
{return 7;}
}

Page ▪ 19
Abstract Class(Contd.)
Example: class TestAbstraction2
abstract class Bike {
{ public static void main(String args[])
Bike() {
{System.out.println("bike is created");} Bike obj = new Honda();
abstract void run(); obj.run();
void changeGear() obj.changeGear();
{System.out.println("gear changed");} }
} }
class Honda extends Bike
{
void run()
{System.out.println("running safely..");}
} Page ▪ 20
Interface in Java
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.
Java Interface also represents IS-A relationship
It cannot be instantiated just like abstract class.

Page ▪ 21
Why use Java interface?
▪ There are mainly three reasons to use interface. They are given below.
It is used to achieve abstraction.
By interface, we can support the functionality of multiple inheritance.
It can be used to achieve loose coupling.
❑ Declaring an interface
An interface is declared by using the interface keyword.
It provides total abstraction; means all the methods in an interface are
declared with the empty body, and all the fields are public, static and final
by default.
A class that implements an interface must implement all the methods
declared in the interface.

Page ▪ 22
Understanding relationship between classes and interfaces
Syntax:
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}

Page ▪ 23
Java Interface Example
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();
}
}
Page ▪ 24
Java Interface Example
interface Bank class TestInterface2
{ {
float rateOfInterest(); public static void main(String[] args)
} {
class SBI implements Bank Bank b=new SBI();
{
public float rateOfInterest() System.out.println("ROI: "+b.rateOfInte
{return 9.15f;} rest());
} }
class PNB implements Bank }
{
public float rateOfInterest()
{return 9.7f;}
}

Page ▪ 25
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple
interfaces, it is known as multiple inheritance.
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.

Page ▪ 26
Multiple inheritance in Java by interface

Page ▪ 27
Interface inheritance
A class implements an interface, but one interface extends another interface.
interface Printable
{
void print();
}
interface Showable extends Printable
{
void show();
}
class TestInterface implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[])
{
TestInterface obj = new TestInterface();
obj.print();
obj.show();
}
}
Page ▪ 28
Abstract Class and Interface
Example:

Page ▪ 29
Difference between Abstract class and Interface

Page ▪ 30
Difference between Abstract class and Interface

Page ▪ 31
Difference between Class and Interface

Page ▪ 32
Packages
A package as the name suggests is a pack(group) of classes, interfaces and
other packages.
In java we use packages to organize our classes and interfaces.
We have two types of packages in Java: built-in packages and the
packages we can create (also known as user defined package).
There are many built-in packages such as java, lang, awt, javax, swing,
net, io, util, sql etc.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they
can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision. For example there can be two
classes with name Employee in two packages, college.staff.cse.Employee
and college.staff.ee.Employee.
Page ▪ 33
Packages

Page ▪ 34
Packages
Package names and directory structure are closely related.
For example if a package name is college.staff.cse, then there are three directories,
college, staff and cse such that cse is present in staff and staff is present college. Also,
the directory college is accessible through CLASSPATH variable, i.e., path of parent
directory of college is present in CLASSPATH. The idea is to make sure that classes are
easy to locate.
Package naming conventions :
Packages are named in reverse order of domain names, i.e., org.abc.practice. For
example, in a college, the recommended convention is college.tech.cse,
college.tech.ee, college.art.history, etc.
▪ Adding a class to a Package : We can add more classes to an created package by
using package name at the top of the program and saving it in the package directory.
We need a new java file to define a public class, otherwise we can add the new class to
an existing .java file and recompile it.
▪Subpackages: Packages that are inside another package are the subpackages. These
are not imported by default, they have to imported explicitly. Also, members of a
subpackage have no access privileges, i.e., they are considered as different package for
Page ▪ 35
protected and default access specifiers.
Packages

Page ▪ 36
Creating Packages
//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}

Page ▪ 37
Creating Packages
How to compile java package
If you are not using any IDE, you need to follow the syntax given below:
javac -d directory javafilename
For example, javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file.
You can use any directory name like /home (in case of Linux), d:/abc (in case of windows)
etc. 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.
▪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.

Page ▪ 38
Creating Packages
To compile:

To run:

Page ▪ 39
Page ▪ 40
Importing 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.

Page ▪ 41
Importing Packages
package pack; package mypack;
public class Demo import pack.*;
{
public void msg() class DemoRun
{
{
System.out.println("Hello");
public static void main(String args[]){
}
Demo obj = new Demo();
}
obj.msg();
}
}

Page ▪ 42
Importing Package
2) Using packagename.classname
If you import package.classname then only declared class of this package
will be accessible.
package pack; package mypack;
public class Demo import pack.Demo;
{
public void msg()
class DemoRun
{
{
System.out.println("Hello");
public static void main(String args[]){
}
Demo obj = new Demo();
}
obj.msg();
}
}
Page ▪ 43
Importing Package
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.

Page ▪ 44
Importing Packages
package pack; package mypack;
public class Demo class DemoRun
{ {
public void msg() public static void main(String args[]){
{
pack.Demo obj = new pack.Demo();
System.out.println("Hello");
obj.msg();
}
}
}
}

Page ▪ 45

You might also like