0% found this document useful (0 votes)
3 views12 pages

Java OOP: Inheritance and Keywords

Inheritance in Java allows a subclass to acquire properties and behaviors from a superclass, promoting code reusability. There are several types of inheritance including single, multilevel, hierarchical, multiple (via interfaces), and hybrid inheritance. Additionally, the document explains the use of the super keyword, differences between method overloading and overriding, abstract classes vs interfaces, exception handling, and string manipulation methods.

Uploaded by

gubbalapavani562
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views12 pages

Java OOP: Inheritance and Keywords

Inheritance in Java allows a subclass to acquire properties and behaviors from a superclass, promoting code reusability. There are several types of inheritance including single, multilevel, hierarchical, multiple (via interfaces), and hybrid inheritance. Additionally, the document explains the use of the super keyword, differences between method overloading and overriding, abstract classes vs interfaces, exception handling, and string manipulation methods.

Uploaded by

gubbalapavani562
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1) What is an Inheritance? Explain types of Inheritance?

Inheritance is a mechanism in Java where one class (the child or subclass)


acquires the properties (fields) and behaviors (methods) of another class (the
parent or superclass). It promotes code reusability and is a key concept of
Object-Oriented Programming (OOP). The keyword used to implement
inheritance is extends.

Types of Inheritance in Java


1.​Single Inheritance: A single subclass extends a single superclass.
2.​Multilevel Inheritance: A class inherits from another class, which in
turn inherits from another class (e.g., Class C \rightarrow Class B
\rightarrow Class A).
3.​Hierarchical Inheritance: Multiple subclasses inherit from a single
superclass (e.g., Class B and Class C both inherit from Class A).
4.​Multiple Inheritance: One class inherits from multiple superclasses.
Java does not support multiple inheritance with classes to avoid the
"Diamond Problem," but it can be achieved using Interfaces.
5.​Hybrid Inheritance: A combination of two or more types of
inheritance. Since Java doesn't support multiple inheritance of classes,
hybrid inheritance is also achieved using a combination of classes and
Interfaces.

2) Explain about application of super keywords?


The super keyword is a reference variable used inside a subclass to refer to
the immediate parent class object.

Applications of the super keyword


Purpose Description Example
1. To refer to the Used when the subclass [Link]
immediate parent class and superclass have a
instance variable (field) variable with the same
name.
2. To invoke the Used when the subclass [Link]()
immediate parent class has overridden a method
method of the superclass and you
Purpose Description Example
want to explicitly call the
superclass's version of
that method.
3. To invoke the Used to call the parent super(), or
immediate parent class class's constructor from super(arguments)
constructor the subclass's constructor.
This must be the first
statement in the subclass
constructor.

3) Difference between method overloading and overriding?


Feature Method Overloading Method Overriding
(Compile-Time (Run-Time
Polymorphism) Polymorphism)
Definition Methods have the same Methods have the same
name but different name and same
parameters (signature) parameters (signature)
within the same class. in the subclass and the
superclass.
Scope Occurs within a single Occurs in two classes
class. that have an inheritance
relationship.
Parameters Must be different (either Must be exactly the
in count, type, or order). same.
Binding Uses Static Binding (or Uses Dynamic Binding
Compile-time binding). (or Run-time binding).
Return Type Can be the same or Must be the same (or a
different. covariant return type in
later Java versions).
Static Methods Can be overloaded. Cannot be overridden
(though you can redefine
a static method in a
subclass, it's called
Feature Method Overloading Method Overriding
(Compile-Time (Run-Time
Polymorphism) Polymorphism)
method hiding, not
overriding).

4) Difference between abstract class and Interfaces?


Feature Abstract Class Interface
Declaration Declared using the Declared using the
abstract keyword. interface keyword.
Implementation A class extends an A class implements an
abstract class. interface.
Inheritance A class can extend only A class can implement
one abstract class. multiple interfaces
(achieving multiple
inheritance of type).
Methods Can have abstract All methods are
methods (without body) implicitly public and
and concrete abstract (before Java 8).
(non-abstract) methods. From Java 8+, they can
also have static and
default methods.
Variables Can have final, non-final, Variables are implicitly
static, and non-static public, static, and final.
variables.
Constructor Can have constructors. Cannot have
constructors.

5) Define package and explain userdefined and predefined


packages?
A package is a mechanism in Java to group related classes, interfaces, and
sub-packages. Think of it as a folder or namespace that helps organize code
and prevent naming conflicts.
Types of Packages
1.​ Predefined Packages (Built-in Packages):
○​ These are packages that come bundled with the Java
Development Kit (JDK) and contain a vast collection of
built-in classes.
○​ Examples:
■​ [Link]: Contains fundamental classes like Object,
String, System, and is imported automatically.
■​ [Link]: Contains utility classes like Scanner, ArrayList,
Date, etc.
■​ [Link]: Contains classes for input/output operations.
■​ [Link], [Link], etc.
2.​ User-Defined Packages:
○​ These are packages created by the programmer to group their
own classes and interfaces for better modularity and
organization.
○​ A package is created using the package keyword as the first
statement in a Java source file.
○​ Example: package [Link];

6) Explain about Enumeration keywords?


The enum (short for enumeration) keyword is used to declare a special type
of class that represents a fixed set of constants.

Key Points about enum


●​ An enum in Java is more than just a list of constants; it's a special class
type.
●​ The constants defined inside an enum are implicitly public static final.
●​ Enums provide type safety, meaning you can only assign one of the
predefined values.
●​ Enums can have constructors, methods, and instance variables,
making them powerful for creating constant-specific behavior.
Example:
enum Day {​
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,
SATURDAY​
}​

public class EnumDemo {​
public static void main(String[] args) {​
Day today = [Link]; // Using a fixed constant​
[Link]("Today is: " + today);​
}​
}​

7) Define Wrapper class and explain types of wrapper classes.


Definition of Wrapper Class
A Wrapper Class in Java is a class whose object wraps or contains a
primitive data type. It allows the primitive data types to be represented as
objects.

Need for Wrapper Classes


They are necessary for:
1.​ Working with collections (like ArrayList), as they store objects, not
primitives.
2.​ Implementing generic programming.
3.​Supporting features like Autoboxing (primitive \rightarrow Wrapper)
and Unboxing (Wrapper \rightarrow primitive).

Types of Wrapper Classes


For every primitive data type in Java, there is a corresponding wrapper class:
Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
Primitive Type Wrapper Class
float Float
double Double
char Character
boolean Boolean

8) Define format specifier class and write a program in date and


time in java.
Format Specifier Class
In Java, there isn't a single class explicitly called "Format Specifier Class."
The concept of format specifiers is primarily used with the printf() method
(from the PrintStream class) and the format() method (from the String and
Formatter classes) to control how data is displayed.
A format specifier is a placeholder sequence that begins with a percent sign
(%) followed by an optional set of flags, width, precision, and a conversion
character (e.g., %d for integer, %s for string, %f for float).
For date and time formatting, the [Link] class uses specific
conversion characters:
●​ %t: Prefix for date/time conversions.
●​ %tF: Full date (e.g., 2025-10-06)
●​ %tD: Date (e.g., 10/06/25)
●​ %tr: Time (12-hour format)
Java Program for Date and Time Formatting
Using the modern Java Date/Time API ([Link]) is the preferred and more
robust approach.
import [Link];​
import [Link];​

public class DateTimeFormatDemo {​
public static void main(String[] args) {​
// 1. Get the current date and time​
LocalDateTime now = [Link]();​

// 2. Define custom format patterns​
DateTimeFormatter customFormat = ​
[Link]("EEEE, MMMM dd, yyyy 'at' hh:mm:ss a");​

// 3. Apply the format​
String formattedDateTime = [Link](customFormat);​

[Link]("Current Unformatted Date/Time: " + now);​
[Link]("Formatted Date/Time: " + formattedDateTime);​

// Example using the Formatter (printf) for a different style:​
[Link]("\nFormatted using printf: %tD %tr%n", now, now);​
}​
}​

9) Define Exception? explain exception handling mechanism.


Definition of Exception
An Exception is an event that occurs during the execution of a program that
disrupts the normal flow of the program's instructions.
●​ Exceptions are objects in Java, primarily derived from the
[Link] class.
●​ Checked Exceptions (e.g., IOException) are checked at compile time.
●​ Unchecked Exceptions or Runtime Exceptions (e.g.,
ArithmeticException) are checked at runtime.

Exception Handling Mechanism


Exception Handling is the process of dealing with runtime errors in a way
that prevents the program from crashing and allows it to continue executing.

The core mechanism involves five keywords:


Keyword Purpose
try The block of code that is expected to
throw an exception is placed inside
the try block.
catch The block that immediately follows
the try block. It contains the code to
handle the exception if one occurs.
Keyword Purpose
finally The block that contains code that must
be executed regardless of whether
an exception occurred or not. It's
typically used for cleanup tasks like
closing resources.
throw Used to explicitly throw an instance
of an exception from a method or
block of code.
throws Used in a method signature to declare
which exceptions a method might
throw, forcing the caller to handle
them.

10) Difference between throw and throws keywords.

Feature throw keyword throws keyword


Purpose Used to explicitly throw Used in a method
an exception object from signature to declare an
a method or block. exception that the
method might throw.
Syntax Followed by an instance Followed by a class
of the Throwable class name of the exception
(e.g., throw new (e.g., throws
ArithmeticException();). IOException,
SQLException).
Usage Used inside a method Used with the method
body. signature.
Quantity You can throw only one You can declare multiple
exception at a time. exceptions
(comma-separated).
11) Write a java program to handle the exception using try and
multiple catch block.
This program demonstrates handling different types of exceptions using a try
block followed by multiple specific catch blocks.

public class MultipleCatchDemo {​


public static void main(String[] args) {​
try {​
String s = null;​
int a = 10;​
int b = 0;​

// Potential ArithmeticException​
int result = a / b; ​
[Link]("Result: " + result); ​

// Potential NullPointerException​
[Link]("String length: " + [Link]()); ​

} catch (ArithmeticException e) {​
// This block handles division by zero​
[Link]("Caught ArithmeticException: Cannot divide by zero.");​

} catch (NullPointerException e) {​
// This block handles operations on a null object​
[Link]("Caught NullPointerException: Object reference is
null.");​

} catch (Exception e) {​
// This is a generic catch block for any other exceptions (must be last)​
[Link]("Caught a generic Exception: " + [Link]());​

} finally {​
// This block always executes​
[Link]("Program finished the try-catch-finally block.");​
}​
}​
}​
Output :

Caught ArithmeticException: Cannot divide by zero.​


Program finished the try-catch-finally block.​

12) What is string? Explain any five string handling functions?


What is a String?
In Java, a String is a sequence of characters. Strings are objects of the
[Link] class. They are immutable, meaning once a String object is
created, its value cannot be changed. Any operation that seems to modify a
String actually creates a new String object.

Five String Handling Functions (Methods)


Function Description Example
1. length() Returns the number of "hello".length() \rightarrow
characters (length) in the 5
string.
2. charAt(int index) Returns the character at "Java".charAt(1)
the specified index. Indices \rightarrow 'a'
start at 0.
3. substring(int start) Returns a new string that is "program".substring(3)
a substring of this string, \rightarrow "gram"
starting from the specified
index to the end.
4. equals(Object Compares the string to the "Hi".equals("hi")
anObject) specified object. Returns \rightarrow false (case
true if the strings are equal sensitive)
in content.
5. indexOf(String str) Returns the index within "applepie".indexOf("pie")
this string of the first \rightarrow 5
occurrence of the
specified substring.
13) Difference between StringBuffer and StringBuilder.
Both StringBuffer and StringBuilder classes are used to create mutable
(changeable) sequences of characters, unlike the String class.

Feature StringBuffer StringBuilder


Mutability Mutable (can be Mutable (can be
changed). changed).
Synchronization Synchronized Non-synchronized (not
(thread-safe). Methods thread-safe).
have an intrinsic lock.
Performance Slower due to the Faster as there is no
overhead of synchronization
synchronization checks. overhead.
Use Case Used in multi-threaded Used in single-threaded
environments where environments where
thread safety is essential. performance is crucial.
Introduced in JDK 1.0. JDK 1.5.

14) Difference between "==" to equals.


In Java, the difference between the equality operator (==) and the equals()
method is fundamental, especially when comparing objects.

Operator/Method == (Equality Operator) equals() method


Type of Comparison Compares references Compares content
(memory addresses) for (values) of two objects.
objects. Compares values
for primitives.
Where it Works Works on primitives Only works on objects (it
(e.g., int, boolean) and is a method inherited
objects. from the Object class).
Default Behavior For objects, it checks if By default, in the Object
both references point to class, it behaves the same
the exact same object in as == (compares
Operator/Method == (Equality Operator) equals() method
memory. references).
Overriding Cannot be overridden Can and should be
for classes. overridden by classes
(like String and all
Wrapper classes) to
provide meaningful
content comparison.

Example with Strings


String s1 = new String("Java");​
String s2 = new String("Java");​
String s3 = s1; // s3 references the same object as s1​

// 1. == comparison​
[Link](s1 == s2); // Output: false (Different objects in memory)​
[Link](s1 == s3); // Output: true (Same object reference)​

// 2. equals() comparison​
[Link]([Link](s2)); // Output: true (Contents are the same)​

You might also like