Java-Unit 2
Java-Unit 2
Inheritance
Basic concepts:
Inheritance is one of the four fundamental concepts of Object-Oriented Programming (OOP), along
with Encapsulation, Abstraction, and Polymorphism.
In Java, inheritance allows a class (called a child class or subclass) to acquire the properties and
behaviors (fields and methods) of another class (called a parent class or superclass).
It enables the reuse of existing code, which improves the modularity and maintainability of the
software system.
Inheritance helps model hierarchical relationships between classes and represents "is-a" relationships.
For instance, a Dog is an Animal, and a Car is a Vehicle.
Class: A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created.
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived
class, extended class, or child class.
Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also
called a base class or a parent class.
Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields
and methods of the existing class when you create a new class. You can use the same fields and
methods already defined in the previous class.
Types of inheritance
There are five types of inheritance available in Java programming. They are as follows:
1. Single level inheritance
2. Multilevel inheritance
3. Hierarchical inheritance
4. Multiple inheritance
5. Hybrid inheritance
In Java programming, multiple inheritance and hybrid inheritance are supported through the interface only.
In java programming, multiple and hybrid inheritance is supported through interface only.
Multiple inheritance is not supported in Java through class.
1.Single Inheritance:
Definition: A subclass inherits from only one superclass. It is the simplest form of inheritance where one class
extends another class.
Key Point: A class can only inherit from one parent class.
Example:
class Animal {
void eat() {
System.out.println("This animal eats food");
}
}
Output:
This animal eats food
The dog barks
2. Multilevel Inheritance:
Definition: A class is derived from another class, which is already a subclass of another class. This forms a
chain of inheritance where a class inherits from a parent class, and that parent class inherits from another class.
Key Point: Involves a series of inheritance in levels, where each level inherits from the class above it.
3. Hierarchical Inheritance:
Definition: Multiple classes inherit from a single superclass. All subclasses share the same parent class but can
have their own additional features or behaviors.
Key Point: Multiple subclasses are derived from the same parent class.
These rules are based on the access modifiers used to declare the members.
Types of Access Modifiers in Java
1. Default (Package-Private):
No keyword required: If you don't specify any access modifier, it’s called default access.
What it means: The member (like a variable or method) is only accessible within the same package.
Other classes outside the package cannot access it.
Where it's used: When you want to keep things accessible only within related classes in the same
package.
Example:
// File: Animal.java (same package)
class Animal {
int age = 5; // Default access (no keyword)
void display() {
System.out.println("Age: " + age);
}
}
2. Private:
What it means: A private member is only accessible within the same class. No other class can access it,
not even subclasses or classes in the same package.
Where it's used: When you want to keep things hidden and only used inside the class, like sensitive
data.
Example:
class Animal {
private int age = 5; // Private access
3. Protected:
What it means: A protected member is accessible within the same package and also
by subclasses (even if the subclass is in a different package).
Where it's used: When you want subclasses to access a member, but don’t want it to be completely
public.
Example
class Animal {
protected int age = 5; // Protected access
4. Public:
What it means: A public member is accessible from anywhere in the program. Any class, inside or
outside the package, can access it.
Where it's used: When you want to allow other classes to access and use this member freely.
Example:
public class Animal {
public int age = 5; // Public access
In java, super keyword is used to access methods of the parent class while this is used to access
methods of the current class.
this keyword is a reserved keyword in java
i.e, we can’t use it as an identifier. It is used to refer current class’s instance as well as static members.
It can be used in various contexts as given below:
to refer instance variable of current class
to invoke or initiate current class constructor
can be passed as an argument in the method call
can be passed as argument in the constructor call
can be used to return the current class instance
Example:
// static variable
static int b = 20;
void GFG()
{
// referring current class(i.e, class RR)
// instance variable(i.e, a)
this.a = 100;
System.out.println(a);
System.out.println(b);
}
Output
100
600
Super keyword:
class Parent {
// instance variable
int a = 10;
// static variable
static int b = 20;
}
Output
10
20
Method overloading:
If a class has multiple methods having same name but different in parameters, it is known as Method
Overloading.
If we have to perform only one operation, having same name of the methods increases the readability
of the program.
Different ways to overload the method
There are two ways to overload the method in java
o By changing number of arguments
o By changing the data type
In Java, Method Overloading is not possible by changing the return type of the method only.
In this example, we have created two methods, first add() method performs addition of two numbers
and second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance for calling
methods.
Example:
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Output:
22
33
In this example, we have created two methods that differs in data type. The first add method receives
two integer arguments and second add method receives two double arguments.
Example:
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Output:
22
24.9
1.If subclass (child class) has the same method as declared in the parent class, it is known as method overriding
in Java.
2.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.
Let's understand the problem that we may face in the program if we don't use method overriding.
Example:
//Java Program to demonstrate why we need method overriding
//Here, we are calling the method of parent class with child
//class object.
//Creating a parent class
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike extends Vehicle{
public static void main(String args[]){
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance
obj.run();
}
}
Output:
Vehicle is running
Abstract class:
Key Points:
Abstract Methods: Must be implemented by subclasses.
Concrete Methods: Can be inherited and used directly by subclasses.
Cannot be Instantiated: You cannot create an object of an abstract class directly.
Constructor: Abstract classes can have constructors that are called by subclass constructors.
Example:
Output:
Woof
The animal is sleeping
Key Points:
Runtime Polymorphism: The method to be called is decided at runtime based on the object being
referred to.
Method Overriding: A subclass provides its own implementation of a method that is already defined
in the superclass.
Superclass Reference: You can have a superclass reference pointing to a subclass object, and the
method that gets called depends on the actual object type at runtime.
Example:
// Superclass
class Animal {
// Method in superclass
public void sound() {
System.out.println("Animal makes a sound");
}
}
// Subclass Dog
class Dog extends Animal {
// Overriding the sound method
public void sound() {
System.out.println("Dog barks");
}
}
// Subclass Cat
class Cat extends Animal {
// Overriding the sound method
public void sound() {
System.out.println("Cat meows");
}
}
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is called blank final
variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be
static also which will be initialized in the static block only. We will have detailed learning of these. Let's first
learn the basics of final keyword.
1. class Bike9{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
7. Bike9 obj=new Bike9();
8. obj.run();
9. }
10. }//end of class
Output:Compile Time Error
Packages
Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.
Package in Java: Definition
In Java, a package is a namespace used to organize classes and interfaces into groups. It helps
in structuring and organizing large codebases, preventing naming conflicts, and making code easier to
maintain and reuse.
In java, the access modifiers define the accessibility of the class and its members. For example, private members
are accessible within the same class members only. Java has four access modifiers, and they are default, private,
In java, the package is a container of classes, sub-classes, interfaces, and sub-packages. The class acts as a
container of data and methods. So, the access modifier decides the accessibility of class members across the
different packages.
In java, the accessibility of the members of a class or interface depends on its access specifiers. The following
table provides information about the visibility of both data members and methods.
🔔 The public members can be accessed everywhere.
🔔 The private members can be accessed only inside the same class.
🔔 The protected members are accessible to every child class (same package or other packages).
🔔 The default members are accessible within the same package but not outside the package.
Example
classParentClass{
int a =10;
publicint b =20;
protectedint c =30;
privateint d =40;
voidshowData(){
System.out.println("Inside ParentClass");
System.out.println("a = "+ a);
System.out.println("b = "+ b);
System.out.println("c = "+ c);
System.out.println("d = "+ d);
}
}
classChildClassextendsParentClass{
voidaccessData(){
System.out.println("Inside ChildClass");
System.out.println("a = "+ a);
System.out.println("b = "+ b);
System.out.println("c = "+ c);
//System.out.println("d = " + d); // private member can't be accessed
}
}
publicclassAccessModifiersExample{
publicstaticvoidmain(String[] args){
}
Importing Packages in java
In java, the import keyword used to import built-in and user-defined packages. When a package has imported, we
can refer to all the classes of that package using their name directly.
The import statement must be after the package statement, and before any other statement.
Using an import statement, we may import a specific class or all the classes from a package.
🔔 Using one import statement, we may import only one package or a class.
🔔 Using an import statement, we can not import a class directly, but it must be a part of a package.
Using an importing statement, we can import a specific class. The following syntax is employed to import a
specific class.
Syntax
import packageName.ClassName;
Let's look at an import statement to import a built-in package and Scanner class.
Example
package myPackage;
importjava.util.Scanner;
publicclassImportingExample{
publicstaticvoidmain(String[] args){
int i = read.nextInt();
In the above code, the class ImportingExample belongs to myPackage package, and it also importing a class
Using an importing statement, we can import all the classes of a package. To import all the classes of the package,
we use * symbol. The following syntax is employed to import all the classes of a package.
Syntax
import packageName.*;
Example
package myPackage;
importjava.util.*;
publicclassImportingExample{
publicstaticvoidmain(String[] args){
int i = read.nextInt();
In the above code, the class ImportingExample belongs to myPackage package, and it also importing all the
classes like Scanner, Random, Stack, Vector, ArrayList, HashSet, etc. from the java.util package.
🔔 The import statement imports only classes of the package, but not sub-packages and its classes.
🔔 We may also import sub-packages by using a symbol '.' (dot) to separate parent package and sub-package.
importjava.util.*;
The above import statement util is a sub-package of java package. It imports all the classes of util package only,
1. Definition of an Interface
In Java, an interface is defined using the interface keyword. It can contain abstract methods (methods without a
body), default methods (with an implementation), static methods, and constants.
// constant
int MAX_AGE = 100;
// static method
static void breathe() {
System.out.println("Breathing...");
}
}
2. Implementing an Interface
A class implements an interface using the implements keyword. The class is required to provide
implementations for all of the interface's abstract methods.
Example:
// Interface definition
interface Animal {
// abstract method (implicitly public and abstract)
void sound();
// constant
int MAX_AGE = 100;
// static method
static void breathe() {
System.out.println("Breathing...");
}
}
3. Extending an Interface
In Java, interfaces can extend other interfaces. When an interface extends another interface, it inherits the
abstract methods of the parent interface and can declare additional abstract methods of its own.
An interface can extend one or more interfaces, similar to how classes can inherit from multiple interfaces.
Example of extending interfaces:
// Mammal interface with walk method
interface Mammal {
void walk();
}
Java exception handling is managed via five keywords: try, catch, throw, throws, and finally. Program
statements that you want to monitor for exceptions are contained within a try block. If an exception
occurs within the try block, it is thrown.
Using catch we can catch this exception and handle it in some relational manner. System-generated
exceptions are automatically thrown by the Java run-time system. To manually throw an exception, use
the keyword throw.
Try -Catch Blocks:
The default exception handler provided by the Java run-time system is useful for debugging; we will
usually want to handle an exception yourself. It provides two benefits. First, it allows you to fix the error;
second, it prevents the program from automatically terminating.
To guard against and handle a run-time error, simply enclose the code that you want to monitor inside a
try block. Immediately following the try block, include a catch clause that specifies the exception type
that you wish to catch.
The following example illustrates the use of simple try and catch statements:
…
…
try
catch (Exception-type e)
{
Example:
To illustrate how easily this can be done, the following program includes a try block and a catch clause
which processes the ArithmeticException generated by the division-by-zero error.
class Error4
int d = 10;
int e = 5;
int f = 5;
int x, y;
try
x = d /(e-f);
catch (ArithmeticException k)
y = d / (e+f);
System.out.println(y);
FINALLY
Java supports another statement known as finally statement that can be used to handle an exception that
is not caught by any of the previous catch statements.
The finally block can be used to handle any exception generated within a try block. It may be added
immediately after the try block or after the last catch block shown as follows:
try
{
statement;
catch(Exception-Type-1 e )
statement;
...
...
catch(Exception-Type-n e)
statement;
finally
statement;
finally creates a block of code that will be executed after a try/catch block has completed and before the
code following the try/catch block.
The finally block will execute whether or not an exception is thrown. If an exception is thrown, the
finally block will execute even if no catch statement matches the exception.
We can use this statement to perform certain housekeeping operations such as closing files and releasing
system resources.
Example:
class Error6
int b = 10;
try
catch (ArrayIndexOutOfBoundsException k)
{
System.out.println ("Array Index Error");
finally
There may be times when we would like to throw our own exceptions. We can do this by using the
keyword throws as follows:
throw new Throwable_subclass;
Example:
Program:
import java.lang.Exception;
super (message);
class TestMyException
try
catch (MyException e)
System.out.println (e.getMessage());
finally
Output:
Caught my exception
I am always here
---------------------------------------------------UNIT 2 COMPLETED------------------------------------------------------