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

Unit_3_Inheritance and Packages

Uploaded by

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

Unit_3_Inheritance and Packages

Uploaded by

shreyd1010
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

Inheritance,Interfaces and

Packages
Chapter 3
Marks-12

1 Prof.A.V.Chechare
Inheritance Basics
 It is the mechanism in java by which one class is
allowed to inherit the features
1.fields/variables/members
and 2.methods/functions
of another class.

 Inheritance is an important pillar of Object


Oriented Programming.

2 Prof.A.V.Chechare
 Super Class:
The class whoes features are inherited is known as
super class(or a base class or a parent class).

 Sub Class:
1.The class that inherits the other class is known as
sub class(or a derived class, extended class, or
child class).
2. The subclass can add its own fields and methods
in addition to the superclass fields and methods.

3 Prof.A.V.Chechare
Need of Inheritance
 Reusability:

4 Prof.A.V.Chechare
Reusability Contd…
1. Inheritance supports the concept of “reusability”,
i.e. we can use the code and features of already
existing class,we can derive our new class from
the existing class.

1. By doing this, we are reusing the fields and


methods of the existing class.

5 Prof.A.V.Chechare
Example in Programming

6 Prof.A.V.Chechare
Syntax
 class derived-class extends base-class
{
//methods and fields
}

7 Prof.A.V.Chechare
 Class base
{
features of base class
}
 Class derived extends base
{
new features of derived class
}

8 Prof.A.V.Chechare
Example
 Base Class
Faculty
 Derived Class
Science

9 Prof.A.V.Chechare
class Faculty
{
float salary=30000;
}
class Science extends Faculty
{
float bonous=2000;
public static void main(String args[])
{
Science obj=new Science();

System.out.println("Salary is:"+obj.salary);
System.out.println("Bonous is:"+obj.bonous);

}
}

10 Prof.A.V.Chechare
Example2
 Base Class
Shape
 Derived Class
Rectangle

11 Prof.A.V.Chechare
Class shape
{
float length,breadth,radius;
}
Class Rectangle extends shape
{
void accept()
{
System.out.println(“Insert length and breadth”);
length=sc.nextFloat();
breadth=sc.nextFloat();
}

void area()
{
float area=length*breadth;
System.out.println(“area=”+area);

}
}
Class demoShape
{
public static void main(String args[])
{
12 Prof.A.V.Chechare
Rectangle r=new Rectangle();
r.accept();
Advantages of Inheritance
1. Application development time is less.
2. Application takes less memory.
3. Application execution time is less.
4. Application performance is enhanced
(improved).
5. Redundancy (repetition) of the code is reduced
or minimized so that we get consistence results
and less storage cost.

13 Prof.A.V.Chechare
Types of Inheritance in Java
 Supported:
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical inheritance
 Unsupported:
1. Multiple Inheritance
2. Hybrid Inheritance

14 Prof.A.V.Chechare
1.Single Inheritance
 When a class extends another one class only then
we call it a single inheritance
 Single inheritance is a easy to understand.

 A: Base Class
 B:Derived Class

15 Prof.A.V.Chechare
2 Multilevel Inheritance
 In Multilevel Inheritance, a derived class will be inheriting
a base class and as well as the derived class also act as
the base class to other class.
 In below image, the class A serves as a base class for the
derived class B, which in turn serves as a base class for
the derived class C

16 Prof.A.V.Chechare
Syntax
Class base
{
//members and functions
}
Class ImmediateDerived extends base
{
//members and functions
}
Class derived extends ImmediateDerived
{
//members and functions
}

17 Prof.A.V.Chechare
Class X
{
public void methodX()
{
System.out.println("Class X method");
}}
Class Y extends X
{
public void methodY()
{
System.out.println("class Y method");
}}
Class Z extends Y
{
public void methodZ()
{
System.out.println("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
obj.methodX();
obj.methodY();
18 Prof.A.V.Chechare
obj.methodZ();
}}
class base
{
base()
{
System.out.println(“Base class”);
}
}
class intermediate extends base
{
intermediate()
{
System.out.println(“Intermediate class”);
}
}
class derived extends intermediate
{
derived()
{
System.out.println(“derived class”);
}
public staticvoid main(String args[])
{
Derived d=new derived();
19 Prof.A.V.Chechare
}
}
class Shape {
public void display()
{
System.out.println("Inside display");
}
}
class Rectangle extends Shape {
public void area()
{
System.out.println("Inside area");
}
}
class Cube extends Rectangle
{
public void volume()
{
System.out.println("Inside volume");
}}
public class Tester
{
public static void main(String[] arguments)
{ Cube cube = new Cube();
cube.display();
20 Prof.A.V.Chechare
cube.area();
cube.volume();
Exercise
 WAP in java to implement multilevel inheritance in
java for accepting marks of sem1,sem2,sem3,
sem4 and calculate avg separately and then
display total average

21 Prof.A.V.Chechare
3.Hierachical Inheritance
 In Hierarchical Inheritance, one class serves as a
superclass (base class) for more than one sub class.
 In below image, the class A serves as a base class for
the derived class B,C and D.

22 Prof.A.V.Chechare
Syntax
Class base
{
//variables and methods
}
Class derived1 extends base
{
//variables and methods
}
Class derived2 extends base
{
//variables and methods
}
Class derived3 extends base
{
//variables and methods
}
23 Prof.A.V.Chechare
Example

Departmental Labs

Compute Mechani Electrical


Civil Lab
r Lab cal Lab Lab

24 Prof.A.V.Chechare
 Departmental Lab
o Area
o Name
o Functioning
 Computer Lab
o Area
o Name
o Functioning
o Instruments
 Mechanical Lab
o Area
o Name
o Functioning
o Machines
 Electrical Lab
o Area
o Name
o Functioning
o CIrcuits

25 Prof.A.V.Chechare
Unsupported Types

1. Multiple Inheritance
2. Hybrid Inheritance

26 Prof.A.V.Chechare
Why multiple inheritance is not
supported in java?

 To reduce the complexity and simplify the


language,
 Consider a scenario where A, B, and C are three
classes. The C class inherits A and B classes. If A
and B classes have the same method and you call
it from child class object, there will be ambiguity
to call the method of A or B class.

27 Prof.A.V.Chechare
Super Keyword
 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.

28 Prof.A.V.Chechare
29 Prof.A.V.Chechare
1.Super to access immediate super
class members
 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.

30 Prof.A.V.Chechare
class Animal
{
String color="white";
}
class Dog extends Animal
{
String color="black";
void printColor()
{
System.out.println(color);
System.out.println(super.color);
}
}
class TestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
d.printColor();
31
}} Prof.A.V.Chechare
2.Super to invoke immediate super
class methods
 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.

32 Prof.A.V.Chechare
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal class TestSuper2
{ {
void eat() public static void main(String args[])
{ {
System.out.println("eating bread..."); Dog d=new Dog();
} d.work();
void bark() }
{ }
System.out.println("barking...");
}
void work()
{
super.eat();
bark();
}
33 } Prof.A.V.Chechare
3.Super to invoke super class
constructor
 The super keyword can also be used to invoke the
parent class constructor.
 As we know well that default constructor is provided
by compiler automatically if there is no constructor.
But, it also adds super() as the first statement.

34 Prof.A.V.Chechare
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();
35 } Prof.A.V.Chechare
}
Method overloading
 Overloading allows different methods to have the
same name, but different signatures
 where the signature can differ by the number of
input parameters or type of input parameters or
both.
 Overloading is related to compile-time (or static)
polymorphism.

36 Prof.A.V.Chechare
public class Sum
{
public int sum(int x, int y)
{
return (x + y);
}
public int sum(int x, int y, int z)
{
return (x + y + z);
}
public double sum(double x, double y)
{
return (x + y);
}
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
37 } Prof.A.V.Chechare
}
Method Overriding
 Overriding is a feature that allows a subclass or
child class to provide a specific implementation
of a method that is already provided by one of its
super-classes or parent classes.
 When a method in a subclass has the same name,
same parameters or signature and same return
type(or sub-type) as a method in its super-class,
then the method in the subclass is said to override
the method in the super-class.
 Method overriding is one of the way by which java
achieve Run Time Polymorphism.

38 Prof.A.V.Chechare
 The version of a method that is executed will be
determined by the object that is used to invoke it.
 Parent class object Parent class method
 Child class object Child class method

39 Prof.A.V.Chechare
class Parent
{
void show()
{
System.out.println("Parent's show()");
}
}
class Child extends Parent
{
void show()
{
System.out.println("Child's show()");
}
}
class Main {
public static void main(String[] args)
{
Parent obj1 = new Parent();
obj1.show();

Parent obj2 = new Child();


obj2.show();
}
}

40 Prof.A.V.Chechare
Interfaces
 An interface is just like Java Class, but it only has
static constants and abstract methods.
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}

41 Prof.A.V.Chechare
 To declare an interface, use interface keyword.
 It is used to provide total abstraction.
 That means all the methods in an interface are
declared with an empty body and are public and
all fields are public, static and final by default.

42 Prof.A.V.Chechare
Example
interface Player
{
final int id = 10;
int move();
}

43 Prof.A.V.Chechare
Points to remember
 Interfaces specify what a class must do and not
how. It is the blueprint of the class.
 An Interface is about capabilities like a Player may
be an interface and any class implementing Player
must be able to (or must implement) move(). So it
specifies a set of methods that the class has to
implement.
 If a class implements an interface and does not
provide method bodies for all functions specified
in the interface, then the class must be declared
abstract.

44 Prof.A.V.Chechare
interface In1 public static void main
{ (String[] args)
final int a = 10;
{
void display();
TestClass t = new
}
TestClass();

class TestClass t.display();


implements In1 System.out.println
{ (a);
public void display() }
{ }
System.out.println(“Int
erface Method
Implemented");
45
} Prof.A.V.Chechare
example2
interface Vehicle
{

void changeGear(int a);


void speedUp(int a);
void applyBrakes(int a);
}

46 Prof.A.V.Chechare
import java.io.*; public void applyBrakes(int
decr)
class Bicycle implements Vehicle{ {
speed = speed - decr;
int speed;
}
int gear;
public void changeGear(int nGear)
{ public void printStates()
gear = nGear; {
} System.out.println("speed: "
+ speed + " gear: " + gear);
public void speedUp(int incr)
}
{
speed = speed + incr; }
}

47 Prof.A.V.Chechare
class Bike implements Vehicle
{
int speed;
int gear;
public void changeGear(int nGear) public void printStates()
{ {
gear = newGear; System.out.println("speed: " +
} speed
public void speedUp(int increment) + " gear: " + gear);
{ }
speed = speed + increment;
} }

public void applyBrakes(int decr)


{
speed = speed - decr;
}

48 Prof.A.V.Chechare
class Demo{ Bike bike = new Bike();

public static void main bike.changeGear(1);


(String[] args) bike.speedUp(4);
{ bike.applyBrakes(3);

Bicycle bicycle = new Bicycle( System.out.println("Bike


); present state :");
bicycle.changeGear(2);
bicycle.speedUp(3); bike.printStates();
bicycle.applyBrakes(1); }
System.out.println("Bicycle }
present state :");

bicycle.printStates();

49 Prof.A.V.Chechare
Multiple Interfaces
 To implement multiple interfaces, separate them
with a comma
interface1 interface2
<interface_name> <interface_name>
{ {
// declare constant // declare constant fields
fields // declare methods that
// declare methods that abstract
abstract // by default.
// by default.
}
}

50 Prof.A.V.Chechare
Class demo implements interface1,interface2
{
//implement methods of interface1

//implement methods of interface2


}

51 Prof.A.V.Chechare
example
interface FirstInterface public void myOtherMethod()
{ {
public void myMethod(); System.out.println("Some other
} text...");
interface SecondInterface }
{ }
public void
myOtherMethod(); class MyMainClass
} {
public static void main(String[]
class DemoClass args)
implements FirstInterface, {
SecondInterface DemoClass myObj = new
{ DemoClass(); myObj.myMethod();
public void myMethod() myObj.myOtherMethod();
{52 Prof.A.V.Chechare }
System.out.println("Some }
Example 2

 Interface bank
method: RoI(Rate of interest)
 Class bank(SBI)
 Class Bank(PNB)

53 Prof.A.V.Chechare
The relationship between classes and interfaces

54 Prof.A.V.Chechare
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.
 Parent Interface
interface Sports
{
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}

55 Prof.A.V.Chechare
 Child Interface:
public interface Football extends Sports
{
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}

56 Prof.A.V.Chechare
 Interface Football will have:
1. public void setHomeTeam(String name);
2. public void setVisitingTeam(String name);
3. public void homeTeamScored(int points);
4. public void visitingTeamScored(int points);
5. public void endOfQuarter(int quarter);

57 Prof.A.V.Chechare
Multiple Inheritance by using
Interface

Showab
Printabl le
e

Demo7

58 Prof.A.V.Chechare
Example2
 Parent class + Parent interface=new class
 Interface exampleInt
 Class parent
Child class
Class newInheritance

59 Prof.A.V.Chechare
Packages In Java
 Package in Java is a mechanism to encapsulate a
group of classes, sub packages and interfaces
 Packages are used for:
1. Packages can be considered as data
encapsulation (or data-hiding).
2. Preventing naming conflicts.
For example there can be two classes with
name Employee in two packages,
college.staff.cse.Employee and
college.staff.ee.Employee

60 Prof.A.V.Chechare
3. Making searching/locating and usage of classes,
interfaces, enumerations and annotations easier

4. Providing controlled access: protected and


default have package level access control.
 A protected member is accessible by classes in
the same package and its subclasses.
 A default member (without any access specifier)
is accessible by classes in the same package only.

61 Prof.A.V.Chechare
Types of Packages
1. Built-in Packages (packages from the Java API)

1. User-defined Packages (create your own


packages)

62 Prof.A.V.Chechare
Built in Packages
 The Java API is a library of prewritten 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.
 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:

63 Prof.A.V.Chechare
examples
1)java.lang
2) java.io
3) java.util
4) java.applet
5) java.awt
6) java.net

64 Prof.A.V.Chechare
Syntax
 Import a single class import
import package.name.Class;

 Import the whole package


import package.name.*;
 Example
1.import java.util.Scanner
2.import java.lang.*;

65 Prof.A.V.Chechare
User Defined Packages
 To create your own package, you need to
understand that Java uses a file system directory
to store them. Just like folders on your computer:

└── root
└── mypack
└── MyPackageClass.java

66 Prof.A.V.Chechare
Syntax
 Each package in Java has its unique name and
organizes its classes and interfaces into a
separate namespace, or name group.

 package nameOfPackage;
it should be the first line in code when you are
writing the code

67 Prof.A.V.Chechare
Steps to create package
Step1:
To create a package, use the package keyword:
package mypack;
class MyPackageClass
{
public static void main(String[] args)
{
System.out.println("This is my package!");
}
}
68 Prof.A.V.Chechare
Step2:
Save the file as MyPackageClass.java, and compile
it:
C:\Users\Your Name>javac -d .
MyPackageClass.java
This forces the compiler to create the "mypack"
package

When we compiled the package in the example


above, a new folder was created, called "mypack".

69 Prof.A.V.Chechare
Step3:
To run the MyPackageClass.java file, write the
following

C:\Users\Your Name>java
mypack.MyPackageClass

70 Prof.A.V.Chechare
Adding classes to package
 Creating our first package:
File name – ClassOne.java
package package_name;
public class ClassOne
{
public void methodClassOne()
{
System.out.println("Hello there its ClassOne");
}
}

71 Prof.A.V.Chechare
 Creating our second package:
File name – ClassTwo.java
package package_one;
public class ClassTwo
{
public void methodClassTwo()
{
System.out.println("Hello there i am ClassTwo");
}
}

72 Prof.A.V.Chechare
 Making use of both the created packages:
File name – Testing1.java

import package_one.ClassTwo;
import package_name.ClassOne;

public class Testing


{
public static void main(String[] args)
{
ClassTwo a = new ClassTwo();
ClassOne b = new ClassOne();
a.methodClassTwo();
b.methodClassOne();
}
}
73 Prof.A.V.Chechare
Adding interfaces to package
 Create one package ex. pack1
 Define interface
 File: int1.java
package pack1;
interface int1
{
void demo();
}

74 Prof.A.V.Chechare
 Into same package import interface
 define another class that will implement interface; file:
new1.java
package pack1;
import pack1.int1;
class new1 implements int1
{
public void demo()
{
System.out.println("Printing....");
}
public static void main(String args[])
{
new1 n1=new new1();
n1.demo();
}
75 }
Prof.A.V.Chechare
 Compile int1.java file
 Javac –d . int1.java

 Compile new1.java file


 Javac –d . new1.java

 Run new1 file


 Java pack1.new1

76 Prof.A.V.Chechare
Using Static Import
 Static import is a feature introduced in Java
programming language ( versions 5 and above )
that allows members ( fields and methods )
defined in a class as public static to be used in
Java code without specifying the class in which
the field is defined.

Following program demonstrates static import :

77 Prof.A.V.Chechare
import static java.lang.System.*;
class StaticImportDemo
{
public static void main(String args[])
{
out.println(“Static Import");
}
}

78 Prof.A.V.Chechare

You might also like