OOPJ_4341602_Unit-3_2023 (1)
OOPJ_4341602_Unit-3_2023 (1)
Purpose of Inheritance
o To promote code reuse i.e. supporting reusability.
o To implement Polymorphism.
In Java, “extends” key-word is used to inherit a class.
Syntax of Java 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.
All the properties of superclass except private properties can be inherit in its subclass using extends
keyword.
Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 1
Object Oriented Programming with JAVA (4341602)| Unit-3
Types of Inheritance
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance (Not supported in java through class)
5. Hybrid Inheritance (also known as Virtual Inheritance) (Not supported in java)
1. Single Inheritance
If a class is derived from a single class, then it is called single inheritance.
Class B is derived from class A
Syntax:
class A //Parent Class A
{
…
}
class B extends A // Child Class B
{
…
}
Example,
class A {
void displayA() {
System.out.println("class A method");
}
}
class B extends A // Single Inheritance - class B is derived from class A
{
void displayB() {
System.out.println("class B method");
}
}
class InheritanceDemo {
public static void main(String[] args) {
B b = new B();
b.displayA();
b.displayB();
}
}
Output:
class A method
class B method
Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 2
Object Oriented Programming with JAVA (4341602)| Unit-3
2. Multilevel Inheritance
Any class is derived from a class which is derived from another class then it is called multilevel
inheritance.
Here, class C is derived from class B and class B is derived from
class A, so it is called multilevel inheritance.
Syntax:
class A // A is parent class of B
{
…
}
class B extends A // B is child class of A
{
…
}
class C extends B // C is child class of B
{
…
}
Example,
class A {
void displayA() {
System.out.println("class A method");
}
}
class B extends A //Single Inheritance - class B is derived from class A
{
void displayB() {
System.out.println("class B method");
}
}
class C extends B // Multilevel Inheritance - class C is derived from class B
{
public void displayC() {
System.out.println("class C method");
}
}
class InheritanceDemo {
public static void main(String[] args) {
C c = new C();
c.displayA();
c.displayB();
Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 3
Object Oriented Programming with JAVA (4341602)| Unit-3
c.displayC();
}
}
Output:
class A method
class B method
class C method
3. Hierarchical Inheritance
If one or more classes are derived from one class, then it is called hierarchical inheritance.
Here, class B, class C and class D are derived from class A.
Syntax:
class A // A is parent class
{
…
}
class B extends A // B is child class of A
{
…
}
class C extends A // C is child class of A
{
…
}
Example,
class A {
void displayA() {
System.out.println("class A method");
}
}
class B extends A // Single Inheritance - class B is derived from class A
{
void displayB() {
System.out.println("class B method");
}
}
class C extends A // Hierarchical Inheritance - Class B and Class C are derived from Class A
{
public void displayC() {
System.out.println("class D method");
Define: Method Overriding. List out Rules for method overriding. Write a java program that
implements method overriding. 07 – Summer-2023, 2024, Winter-2024(04)
Describe: Polymorphism. Explain run time polymorphism with suitable example in java. 07 –
Summer-2023
Method Overriding
When a method in a subclass has the same name and type signature as method in its superclass, then
the method in the subclass is said to override the method of the superclass.
Method overriding is used for runtime polymorphism.
Basics of Polymorphism
Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism means “many forms”.
Advantages of Polymorphism
Code Reusability: Polymorphism provides the reuse of code, as methods with the same name can be
used in different classes.
Flexibility and Dynamism: Polymorphism allows for more flexible and dynamic code, where the
behavior of an object can change at runtime depending on the context in which it is being used.
Reduced Complexity: It can reduce the complexity of code by allowing the use of the same method
name for related functionality, making the code easier to read and maintain.
Simplified Coding: Polymorphism simplifies coding by reducing the number of methods and
constructors that need to be written.
Better Organization: Polymorphism allows for better organization of code by grouping related
functionality in one class.
Code Extensibility: Polymorphism enables code extensibility; as new subclasses can be created to
extend the functionality of the superclass without modifying the existing code.
Increased Efficiency: Compile-time polymorphism can lead to more efficient coding. The compiler can
choose the appropriate method to call at compile time, based on the number, types, and order of
arguments passed to it.
Object class
The Object class is the parent class (java.lang.Object) of all the classes in java by default.
Every class in java directly or indirectly derived from Object class.
The Object class is beneficial if you want to refer any object whose type you don't know.
Notice that parent class reference variable can refer the child class object, known as Upcasting.
The Object class provides some common behaviors to all the objects such as object can be compared,
object can be cloned, object can be notified etc.
Methods of Object class:
Method Description
public boolean equals(Object obj) Compares the given object to this object.
Returns a runtime representation of the class of this
public final Class getClass() object. By using this class object we can get information
about class such as its name, its superclass etc.
public String toString() Returns the string representation of this object.
public final void notify() Wakes up single thread, waiting on this object's monitor.
Wakes up all the threads, waiting on this object's
public final void notifyAll()
monitor.
Causes the current thread to wait for the specified
public final void wait(long timeout) throws
milliseconds, until another thread notifies (invokes
InterruptedException
notify() or notifyAll() method).
What is interface? Explain multiple inheritance with example. 07 - Winter-2023, 2024, Summer-
2024
Describe: Interface. Write a java program using interface to demonstrate multiple inheritance. 07
- Summer-2023
Interface - An interface is a collection of abstract methods. An interface is not a class.
When you create an interface it defines what a class can do without saying anything about how the
class will do it.
It is used to achieve fully abstraction and multiple inheritance in Java.
Rules for interface:
o Interface contains only static constants and abstract methods only.
o All variables declared inside interface are public, static and final variable by default
(Implicitly).
o All methods declared inside interface are public and abstract even if you don’t use.
o Interface can extend one or more other interface.
o Interface can’t implement a class.
Similarity between class and interface are given below:
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.
Sr.
Class Interface
No.
1 Object of class can be created. Object of interface can’t be created.
2 It can contain constructors. It cannot contain constructors.
3 It cannot contain abstract methods. It contains abstract methods only.
4 Variables in a class can be static, final, or neither. All variables are static and final.
5 Classes do not support multiple inheritance. The interface supports multiple inheritance.
It can be inherited by a class by using the
It can be inherited by another class using the
6 keyword ‘implements’ and it can be inherited by
keyword ‘extends’.
an interface using the keyword ‘extends’.
Declaring Interfaces
The interface keyword is used to declare an interface.
Syntax: NameOfInterface.java
interface Interface_Name{
// Any number of final, static fields
// Any number of abstract method declarations
// Declare default method (optional)
// Declare static method (optional)
}
Example: DemoInterface.java
interface DemoInterface{
int i = 10; // complier take as public static final int i=10;
void demo(); // complier take as public abstract void demo();
}
Implementing Interfaces
A class uses the implements keyword to implement an interface.
A class implements an interface means, 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.
Syntax:
class classname implements interface_name
{
// Class-body (must implement or defines all abstract methods of the interface)
}
Example1,
interface InterfaceDemo {
int a = 10; // public, static and final variable
void display(); // public and abstract method
}
class InterfaceDemo1 implements InterfaceDemo {
Extending Interfaces
We all knows a class can extend another class. Same way an interface can extend another interface.
The extends keyword is used to extend an interface, and the child interface inherits the methods of the
parent interface.
Example,
interface InterfaceA {
Example,
interface Printable2 {
lambda expression
Lambda expression is a new and important feature of Java which was included in Java SE 8. It provides
a clear and concise way to represent one method interface using an expression. It is very useful in
collection library. It helps to iterate, filter and extract data from collection.
The Lambda expression is used to provide the implementation of an interface which has functional
interface. It saves a lot of code. In case of lambda expression, we don't need to define the method again
for providing the implementation. Here, we just write the implementation code.
Java lambda expression is treated as a function, so compiler does not create .class file.
Functional Interface - Lambda expression provides implementation of functional interface. An interface
which has only one abstract method is called functional interface.
Why use Lambda Expression?
o To provide the implementation of Functional interface.
o Less coding.
Lambda Expression Syntax: (argument-list) -> {body}
Example,
interface Interface1 {
public String print(String name);
}
public class LambdaExperssion {
What is package? Write steps to create a package and give example of it. 07 - Winter-2023,
Winter-2024, Summer-2023(04), 2024
Package - Packages are similar to folders, which are mainly used to organize classes and interfaces.
Department of Information Technology [Ms. N. A. Patel & Mrs. A. K. Virani] 22
Object Oriented Programming with JAVA (4341602)| Unit-3
A package is a group of similar types of classes, interfaces and sub-packages.
Packages are used to prevent naming conflicts and provides access protection.
We can also categorize the package by using concept of subpackage.
Package inside the package is called the sub-package.
Package can be categorized in two form:
i. Built-in packages (Pre-defined package): Existing Java package such as java.lang, java.util,
java.io, java.net, java.awt etc.
ii. User-defined-package: Java package created by user to categorized classes and interface
Programmers can define their own packages to bundle group of classes, interfaces etc.
Creating a package:
Syntax:
package package_name;
//body
OR
package package_name.subpackage_name;
//body
Note: The package statement should be the first line in the source file. There can be only one package statement in
each source file.
If a package statement is not used then the class, interfaces etc. will be put into an unnamed package.
Example of Creating Package,
package com;
1) By using packagename.* :
If you use packagename.* then all the classes and interfaces of this package will be accessible but not
subpackages.
Syntax: import packagename.*;
Example,
Classone.java
package com;
public class Classone {
public void msg() {
System.out.println("Welcome to classone");
2) By using packagename.classname
If you use packagename.classname then only declared class of this package will be accessible.
Syntax: import packagename.classname;
Example,
Classone.java
package com;
public class Classone {
public void msg() {
System.out.println("Welcome to classone");
}
}
Classtwo.java
package tdec;
import com.Classone;
public class Classtwo {
public static void main(String[] args) {
Classone obj=new Classone();
Static Import - The static import feature of Java 5 facilitates the java programmer to access any static
member of a class directly. There is no need to qualify it by the class name.
Advantage of static import: Less coding is required if you have access any static member of a class
often.
Disadvantage of static import: If you overuse the static import feature, it makes the program
unreadable and unmaintainable.
Example,
import static java.lang.System.*;
class StaticImportDemo{
public static void main(String args[]){
out.println("Hello"); //Now no need of System.out
out.println("Java");
}
}
Output:
Hello
Java
Explain different access visibility controls used in Java. 04 – Summer-2023, Winter-2023, 2024
Access modifier, Access and class hiding rules in a package.
Access modifiers is the process of controlling visibility of a variable or method.
Access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class.
There are four levels of visibility:
1. Private – Accessed only within class.
2. Public - Accessed from within class, outside class, within package and outside package.
3. Protected - Accessed only by classes that are subclass of class directly, Visible to package and all
sub Classes.
4. Default (or Package) - Visible to package. No modifiers are needed.
outside package by
Access Modifier within class within package outside package
subclass only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
**********