OOP-Java_Unit-2
OOP-Java_Unit-2
com/@SravanKumarGurram
OBJECT ORIENTED
PROGRAMMING THROUGH JAVA
UNIT-2
Inheritance, Packages and Interfaces
1
www.youtube.com/@SravanKumarGurram
INHERITANCE
CHAPTER – 1
2
INHERITANCE IN JAVA
Inheritance is one of the key features of Object Oriented
Programming.
m
www.youtube.com/@SravanKumarGurra
inherit properties of another class.
m
www.youtube.com/@SravanKumarGurra
The substitutability means that when a child class
acquires properties from its parent class, the object of the
parent class may be substituted with the child class object.
For example, if B is a child class of A, anywhere we expect
an instance of A we can use an instance of B.
Specification
m
www.youtube.com/@SravanKumarGurra
Construction
Extension
Limitation
Combination
8
Specialization:
m
www.youtube.com/@SravanKumarGurra
Ex1:
m
www.youtube.com/@SravanKumarGurra
In this form of inheritance, the parent class
just specifies which methods should be
available to the child class but doesn't
implement them.
The java provides concepts like abstract and
interfaces to support this form of inheritance. 10
Construction:
This is another form of inheritance where the child
class may change the behavior defined by the
m
www.youtube.com/@SravanKumarGurra
parent class (overriding).
Extension
This is another form of inheritance where the child
class may add its new properties.
11
Limitation
m
www.youtube.com/@SravanKumarGurra
final keyword can be used in many context. Final can be:
Variable Ex: final int speedlimit=90; //final variable
Method. If you make any method as final, you cannot
override it.
Ex: final void run()
{
System.out.println("running");
} 12
final class Bike
{
void run() {…..}
} Output:
m
www.youtube.com/@SravanKumarGurra
void run( )
{
System.out.println("running safely with 100kmph");
}
m
www.youtube.com/@SravanKumarGurra
parent classes.
14
www.youtube.com/@SravanKumarGurra
m
15
TYPES OF INHERITANCE
m
www.youtube.com/@SravanKumarGurra
Note: Multiple inheritance is not supported in
Java through class. 16
SINGLE INHERITANCE EXAMPLE
When a class is created from single base class, it is
known as a single inheritance.
m
www.youtube.com/@SravanKumarGurra
Output:
a=10
17
MULTILEVEL INHERITANCE
m
www.youtube.com/@SravanKumarGurra
inheritance.
For example
18
www.youtube.com/@SravanKumarGurra
m
19
Output:
a=10
b=10
HIERARCHICAL INHERITANCE
When a class is extended by two or
more classes, it forms hierarchical
inheritance.
For example, class B extends to
m
www.youtube.com/@SravanKumarGurra
class A and class C also extends to
class A in that case both B and C
share properties of class A.
Output:
a = 10
a = 10 20
SUPER KEYWORD
m
www.youtube.com/@SravanKumarGurra
21
SUPER KEYWORD CONTD…
m
www.youtube.com/@SravanKumarGurra
To call methods of the superclass that is overridden in the
subclass.
class Animal
{
void eat()
{
System.out.println("Animal is eating");
}
m
www.youtube.com/@SravanKumarGurra
}
void display()
{ 23
super.eat(); // Calls the parent class eat() method
}
Ex: Accessing Parent Class Method Using Super Keyword contd..
m
www.youtube.com/@SravanKumarGurra
}
}
Output:
Animal is eating
24
Ex: Accessing Parent Class Field using Super keyword
class Animal
{ Output:
String color = “White"; Black
} White
m
www.youtube.com/@SravanKumarGurra
{
String color = “Black";
void printColor()
{
System.out.println(color); // Prints color of Dog class (black)
System.out.println(super.color); // Prints color of Animal class (white)
}
m
www.youtube.com/@SravanKumarGurra
class Dog extends Animal
{
Dog()
{
super(); // Calls the parent class constructor
System.out.println("Dog is created");
}
m
www.youtube.com/@SravanKumarGurra
specific definition.
m
www.youtube.com/@SravanKumarGurra
The key benefit of overriding is the ability to define
method that's specific to a particular subclass
type.
29
RULES FOR METHOD OVERRIDING
1. Method name must be same for both parent and child
classes.
m
www.youtube.com/@SravanKumarGurra
3. There must be an IS-A relationship between classes
(inheritance).
m
www.youtube.com/@SravanKumarGurra
As you can see here Dog class gives it own implementation of eat() method.
31
For method overriding, the method must have same name and same type
signature in both parent and child class.
class Animal
{
public void eat()
{
System.out.println("Eat all eatables");
}
}
m
www.youtube.com/@SravanKumarGurra
class Dog extends Animal
{
protected void eat() //error
{
System.out.println("Dog like to eat meat");
}
m
www.youtube.com/@SravanKumarGurra
simply we can’t create a child class for final
class.
34
Example program to implement final keyword with inheritance
m
www.youtube.com/@SravanKumarGurra
System.out.println("num = " + num);
}
}
} Error: 35
} ChildClass.java: error: cannot
inherit from final ParentClass
BENEFITS OF INHERITANCE IN JAVA
❖ The biggest advantage of inheritance is code
reusability, since the fields and methods of parent class
get's inherited in child class, the child class won't have to
m
www.youtube.com/@SravanKumarGurra
create it again. It can access those features of parent
class from the child class, that is what the code
reusability is.
m
www.youtube.com/@SravanKumarGurra
❖ Using inheritance we can achieve runtime
polymorphism(method overriding).
37
COSTS OF INHERITANCE/DISADVANTAGES
❖ No Independence:
m
www.youtube.com/@SravanKumarGurra
is that two classes, both the base and inherited class,
get tightly bounded by each other.
38
COSTS OF INHERITANCE/DISADVANTAGES
CONTD..
m
www.youtube.com/@SravanKumarGurra
speed because Inheritance execution takes time
and effort.
39
www.youtube.com/@SravanKumarGurram
CHAPTER-2
PACKAGES
40
JAVA PACKAGE
Package is a collection of related classes. Java uses
package to group related classes, interfaces and sub-
packages in any Java project.
m
www.youtube.com/@SravanKumarGurra
We can assume package as a folder or a directory
that is used to store similar files.
In Java, packages are used to avoid name conflicts
and to control access of class, interface etc.
Using package it becomes easier to locate the related
classes and it also provides a good structure for projects
41
with hundreds of classes and other files.
TYPES OF JAVA PACKAGE
m
www.youtube.com/@SravanKumarGurra
Built-in Package: java.util, java.lang, java.io etc
are the example of built-in packages.
42
m
www.youtube.com/@SravanKumarGurra
Hierarchy of Java Built-in Packages
43
HOW TO IMPORT JAVA PACKAGE
To import java package into a class, we need to use
java import keyword which is used to access package and
its classes into the java program.
m
www.youtube.com/@SravanKumarGurra
Use import keyword to access built-in and user-defined
packages into your java source file so that your class can
refer to a class that is in another package by directly using
its name.
import package with specified class
import PackageName.ClassName;
import package with all classes
44
import PackageName.*;
HOW TO CREATE A USER DEFINED PACKAGE
m
www.youtube.com/@SravanKumarGurra
by name of the package as the first
statement in java source file.
45
ADDITIONAL POINTS ABOUT PACKAGE:
Package statement must be first statement in the
program even before the import statement.
m
www.youtube.com/@SravanKumarGurra
Store all the classes in that package folder.
javac -d . ClassName.java
m
www.youtube.com/@SravanKumarGurra
The -d specifies the destination where to put the
generated class file.
You can use any directory name like d:/abc (in case
of windows) etc.
47
//save by Demo.java
package pack; //Creating a package pack
public class Demo
{ Step-1: Compile Demo.java
public void msg() javac –d . Demo.java
{
Step-2: write the code Test.java
System.out.println("Hello"); code in a new file
}
m
www.youtube.com/@SravanKumarGurra
} Step-3: run Test.java
//save by Test.java
import pack.Demo; //Importing Demo class from pack Packages
class Test
{
public static void main(String args[])
{
Demo obj = new Demo();
obj.msg();
} Output: 48
} Hello
JAVA ABSTRACT CLASS AND METHODS
A class which is declared using abstract
keyword known as abstract class. We cannot create
object for the abstract class.
m
www.youtube.com/@SravanKumarGurra
It is used to achieve abstraction but it does not provide
100% abstraction because it can have Non-Abstract
methods also.
It can have abstract and non-abstract methods.
Syntax: abstract class class_name
{
.......
49
}
EX: ABSTRACT CLASS DECLARATION
m
www.youtube.com/@SravanKumarGurra
//This is abstract method
abstract void myMethod(); // doesn’t have a body
m
www.youtube.com/@SravanKumarGurra
Abstract method can never be final.
Any class that extends an abstract class must implement all the
abstract methods.
If any class has even a single abstract method, then it must be
declared abstract.
Syntax:
abstract return_type Method_name ();
//No definition 51
WHY WE NEED AN ABSTRACT CLASS?
m
www.youtube.com/@SravanKumarGurra
Since the animal sound differs from one animal to another,
there is no point to implement this method in parent class.
m
www.youtube.com/@SravanKumarGurra
//Dog class extends Animal class
public class Dog extends Animal Woof
{
54
JAVA INTERFACES
Interface is a concept which is used to achieve
abstraction in Java. This is the only way by which we
can achieve full abstraction.
Interfaces are syntactically similar to classes, but you
m
www.youtube.com/@SravanKumarGurra
m
www.youtube.com/@SravanKumarGurra
implicitly public and abstract, even if you don't
use public or abstract keyword.
57
m
www.youtube.com/@SravanKumarGurra
NOTE:
Compiler automatically converts methods of
Interface as public and abstract.
58
Program to implement interface
Output:
Average speed is 40.
m
www.youtube.com/@SravanKumarGurra
59
MULTIPLE INHERITANCE IN JAVA BY
INTERFACE
m
www.youtube.com/@SravanKumarGurra
60
interface Printable
{ Ex_1: Program to implement Multiple
void print(); inheritance
}
interface Showable Interface Interface
{
void show();
}
class A7 implements Printable,Showable
m
www.youtube.com/@SravanKumarGurra
{ Class
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome"); Output:
}
public static void main(String args[]) Hello
{ Welcome
A7 obj = new A7();
obj.print(); 61
obj.show();
} }
// Base class Ex_2: Program to implement Multiple
class Animal { inheritance
void eat() {
System.out.println("Animal is eating");
}
}
Class Interface
// Interface
interface Pet {
m
www.youtube.com/@SravanKumarGurra
void play();
}
Class
// Derived class
class Dog extends Animal implements Pet {
public void play() {
System.out.println("Dog is playing");
} Output:
Animal is eating
public static void main(String[] args) { Dog is playing
Dog d = new Dog();
d.eat(); // Calls method from Animal class
d.play(); // Calls method from Pet interface 62
}
}
NESTED INTERFACES
An interface, declared within another interface
or class, is known as a nested interface.
m
www.youtube.com/@SravanKumarGurra
The nested interfaces are used to group related
interfaces so that they can be easy to maintain.
63
NESTED INTERFACES
Syntax:
m
www.youtube.com/@SravanKumarGurra
{
...
interface nested_interface_name // Inner Interface
{
...
}
}
64
Example Program to implement Nested Interface.
Create an interface within the class
class OuterClass{ Output:
This is InnerInterface
interface InnerInterface{ method
void innerMethod();
}
}
m
www.youtube.com/@SravanKumarGurra
class ImplementingClass implements OuterClass.InnerInterface
{
public void innerMethod() {
System.out.println("This is InnerInterface method");
}
}
public class NestedInterfaceExample {
m
www.youtube.com/@SravanKumarGurra
class ImplementingClass implements OuterInterface,
OuterInterface.InnerInterface {
public void outerMethod() {
System.out.println("Outer method implementation");
}
m
www.youtube.com/@SravanKumarGurra
The interface that extends another interface has its
own members and all the members defined in its
parent interface too.
interface ParentInterface
{
void parentMethod();
}
m
www.youtube.com/@SravanKumarGurra
interface ChildInterface extends ParentInterface
{
void childMethod(); Parent Interface
}
child Interface
68
Implementing
Class
Example Program to implement Extended Interface Contd..
m
www.youtube.com/@SravanKumarGurra
System.out.println("Child Interface method");
}
m
www.youtube.com/@SravanKumarGurra
ImplementingClass obj = new
ImplementingClass();
obj.childMethod();
obj.parentMethod();
} Output:
Child Interface Method 70
m
www.youtube.com/@SravanKumarGurra
Interface variables are static because java interfaces
cannot be instantiated on their own. The value of the
variable must be assigned in a static context in which
no instance exists.
The final modifier ensures the value assigned to the
interface variable is a true constant that cannot be re-
assigned. In other words, interfaces can declare only
71
constants, not instance variables.
interface Moveable
{
int AVG_SPEED = 40; // Implicitly public, static and final
void move();
}
m
www.youtube.com/@SravanKumarGurra
{
AVG_SPEED = 50;
System .out. println("Average speed is"+AVG_SPEED);
}
public static void main (String[] arg)
{
Vehicle vc = new Vehicle();
vc.move();
}
}
Output:
Error: 72
Vehicle.java:11: error: cannot assign a value to final variable
AVG_SPEED
I/O STREAMS: JAVA.IO
Accept input from the user
InputStreamReader Class
www.youtube.com/@SravanKumarGurram
BufferedReader Class
73
Output:Enter your name Amit Welcome Amit
Output:
import java.io.*;
class Input Enter your name Bose
Welcome Bose
{
public static void main(String args[]) throws Exception
{
m
www.youtube.com/@SravanKumarGurra
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
m
www.youtube.com/@SravanKumarGurra
When the Scanner Class receives input, it breaks the input
into several pieces, called tokens.
These tokens can be retrieved from the Scanner Object using
the following methods
nextLine( ) ---- to read a string
nextInt( ) ----- to read Int Values
nextFloat( ) ----- to read Float Values
next().charAt(0) ---- to read Char value 76
import java.util.Scanner; Java Program to implement Scanner to class
to read String, int and double values
class InputScan
{
public static void main(String[ ] args)
{
Scanner sc = new Scanner(System.in);
m
www.youtube.com/@SravanKumarGurra
System.out.println("Enter name, age and salary:");
// String input
String name = sc.nextLine(); Output:
Enter name, age and salary:
// Numerical input Ramu
int age = sc.nextInt(); 25
double salary = sc.nextDouble(); 6.5
import java.util.Scanner;
public class ReadCharacter
{
m
www.youtube.com/@SravanKumarGurra
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a character: ");
char ch = scanner.next().charAt(0);
System.out.println("You entered: " + ch);
} 78
}
JAVA FILE CLASS
m
www.youtube.com/@SravanKumarGurra
A file is a named location that can be used to store
related information.
m
www.youtube.com/@SravanKumarGurra
File fileObj = new File(String pathName);
Package and
Operation Method
class
m
www.youtube.com/@SravanKumarGurra
To create file createNewFile() java.io.File
81
JAVA CREATE FILES
m
www.youtube.com/@SravanKumarGurra
It returns true if a new file is created.
82
// importing the File class
import java.io.File;
class Main {
public static void main(String[] args) {
m
www.youtube.com/@SravanKumarGurra
try {
m
www.youtube.com/@SravanKumarGurra
Here, we have used the file object to create the new
file with the specified path.
m
www.youtube.com/@SravanKumarGurra
displayed as an
FileReader input = new FileReader("input.txt"); output of this
program
// Reads characters
input.read(array);
System.out.println("Data in the file:");
System.out.println(array);
m
www.youtube.com/@SravanKumarGurra
// Creates a Writer using FileWriter
FileWriter output = new FileWriter("output.txt");