Java Classes and Objects Explained
Java Classes and Objects Explained
A class is a blueprint from which individual objects are created (or, we can say a class is a data type of an object type).
In Java, everything is related to classes and objects. Each class has its methods and attributes that can be accessed and
manipulated through the objects.
For example, if you want to create a class for students. In that case, "Student" will be a class, and student records
(like student1, student2, etc) will be objects.
A class is just like a real-world entity, but it is not a real-world entity. It's a blueprint where we specify the
functionalities.
Classes follow all of the rules of OOPs such as inheritance, encapsulation, abstraction, etc.
Local variables − Variables defined inside methods, constructors or blocks are called local variables. The
variable will be declared and initialized within the method and the variable will be destroyed when the method
has completed.
Instance variables − Instance variables are variables within a class but outside any method. These variables are
initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor
or blocks of that particular class.
Class variables − Class variables are variables declared within a class, outside any method, with the static
keyword.
To create (declare) a class, you need to use access modifiers followed by class keyword and class_name.
In this example, we are creating a class "Dog". Where, the class attributes are breed, age, and color. The class methods
are setBreed(), setAge(), setColor(), and printDetails().
class Dog {
String breed;
int age;
String color;
[Link] = breed;
[Link] = age;
[Link] = color;
[Link]("Dog detials:");
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
If we consider the real world, we can find many objects around us, cars, dogs, humans, etc. All these objects have a
state and a behavior.
If we consider a dog, then its state is - name, breed, and color, and the behavior is - barking, wagging the tail, and
running.
If you compare the software object with a real-world object, they have very similar characteristics. Software objects
also have a state and a behavior. A software object's state is stored in fields and behavior is shown via methods. So, in
software development, methods operate on the internal state of an object, and the object-to-object communication is
done via methods.
As mentioned previously, a class provides the blueprints for objects. So basically, an object is created from a class. In
Java, the new keyword is used to create new objects.
Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object.
Note: parameters are optional and can be used while you're using constructors in the class.
In this example, we are creating an object named obj of Dog class and accessing its methods.
String color;
// methods to set breed, age, and color of the dog
[Link] = breed;
[Link] = age;
[Link] = color;
[Link]("Dog detials:");
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link](2);
[Link]("Golden");
}
}
Output
Dog detials:
Golden Retriever
Golden
Let's now look into the source file declaration rules (to use the Java classes & objects approach). These rules are
essential when declaring classes, import statements, and package statements in a source file.
The public class name should be the name of the source file as well which should be appended by .java at the
end. For example − the class name is public class Employee{} then the source file should be as [Link].
If the class is defined inside a package, then the package statement should be the first statement in the source
file.
If import statements are present, then they must be written between the package statement and the class
declaration. If there are no package statements, then the import statement should be the first line in the source
file.
Import and package statements will imply to all the classes present in the source file. It is not possible to declare
different import and/or package statements to different classes in the source file.
Classes have several access levels and there are different types of classes; abstract classes, final classes, etc. We will be
explaining about all these in the access modifiers chapter.
Apart from the above mentioned types of classes, Java also has some special classes called Inner classes and
Anonymous classes.
Example 1
The Employee class has four instance variables - name, age, designation and salary. The class has one explicitly
defined constructor, which takes a parameter.
CLASS OVERVIEW
String name;
int age;
String designation;
double salary;
These are instance variables — each Employee object will have its own copy of these:
CONSTRUCTOR
[Link] = name;
The constructor initializes the name of the employee when a new object is created.
Example:
Setter Methods
age = empAge;
designation = empDesig;
}
public void empSalary(double empSalary) {
salary = empSalary;
They work like setters, allowing you to set values for age, designation, and salary after the object is created.
� Display Method
[Link]("Name:" + name);
[Link]("Age:" + age);
[Link]("Designation:" + designation);
[Link]("Salary:" + salary);
� Example Usage
You’d usually create another class (say, [Link]) to create and use Employee objects:
[Link](30);
[Link]("Software Developer");
[Link](60000);
[Link]();
Output:
Name:John
Age:30
Designation:Software Developer
Salary:60000.0
In Java, Method Overloading allows a class to have multiple methods with the same name but different parameters,
enabling compile-time (static) polymorphism.
Methods can share the same name if their parameter lists differ.
The compiler chooses the most specific match when multiple methods could apply.
Method overloading can be achieved by changing the number of parameters while passing to different methods.
import [Link].*;
class Product{
int prod = a * b;
return prod;
return prod;
class Geeks{
[Link](
[Link](
Output
Explanation:
Two methods have the same name but different number of parameters.
Compiler selects the correct method based on how many arguments are passed.
2. Changing Data Types of Parameters
In many cases, methods can be considered overloaded if they have the same name but have different parameter types,
methods are considered to be overloaded.
class Product{
return a * b * c;
return a * b * c;
[Link]([Link](1, 2, 3));
Output
6.0
Explanation:
Compiler matches the method based on the exact data type of arguments.
3. Changing the Order of Parameters
Method overloading can also be implemented by rearranging the parameters of two or more overloaded methods.
class Student {
[Link]("Sweta", 1);
[Link](2, "Gudly");
Output
An instance of an inner class cannot be created without an instance of the outer class. Therefore, an inner class instance
can access all of the members of its outer class, without using a reference to the outer class instance. For this reason,
inner classes can help make programs simple and concise.
The following are major differences between static nested classes and inner classes.
1. A static nested class may be instantiated without instantiating its outer class.
2. Inner classes can access both static and non-static members of the outer class. A static class can access only the
static members of the outer class.
// Class 1
// Helper class
class OuterClass {
// Input string
// static class
[Link](
// called
[Link](
+ msg);
// Class 2
// Main class
class GFG {
[Link] printer
= new [Link]();
// static class
[Link]();
[Link] inner
= [Link] InnerClass();
[Link]();
[Link] innerObject
[Link]();
Output
Message from nested static class: Static and Non Static Class
Message from non-static nested class: Static and Non Static Class
Message from non-static nested class: Static and Non Static Class
Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It
is an important part of OOPs (Object Oriented programming system).
The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you
inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new
methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
o Class: A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created.
o 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.
o 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.
o 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.
}
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.
As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The relationship between
the two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee.
class Employee{
float salary=40000;
int bonus=10000;
}
}
In the above example, Programmer object can access the field of own class as well as of Employee class i.e. code
reusability.
On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about
interfaces later.
When one class inherits multiple classes, it is known as multiple inheritance. For Example
Single Inheritance Example
When a class inherits another class, it is known as a single inheritance. In the example given below, Dog class inherits
the Animal class, so there is the single inheritance.
File: [Link]
class Animal{
void eat(){[Link]("eating...");}
void bark(){[Link]("barking...");}
class TestInheritance{
[Link]();
[Link]();
Output:
barking...
eating...
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given below,
BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel inheritance.
File: [Link]
class Animal{
void eat(){[Link]("eating...");}
void bark(){[Link]("barking...");}
void weep(){[Link]("weeping...");}
class TestInheritance2{
[Link]();
[Link]();
[Link]();
Output:
weeping...
barking...
eating...
Hierarchical Inheritance Example
When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example given below,
Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.
File: [Link]
class Animal{
void eat(){[Link]("eating...");}
void bark(){[Link]("barking...");}
void meow(){[Link]("meowing...");}
class TestInheritance3{
[Link]();
[Link]();
//[Link]();//[Link]
}}
Output:
meowing...
eating...
}
Compile Time Error
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.
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.
class Animal{
String color="white";
void printColor(){
class TestSuper1{
[Link]();
}}
Output:
black
white
In the above example, Animal and Dog both classes have a common property color. If we print color property, it will
print the color of current class by default. To access the parent property, we need to use super keyword.
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.
class Animal{
void eat(){[Link]("eating...");}
[Link]();
bark();
class TestSuper2{
[Link]();
}}
Output:
eating...
barking...
In the above example Animal and Dog both classes have eat() method if we call eat() method from Dog class, it will
call the eat() method of Dog class by default because priority is given to local.
The super keyword can also be used to invoke the parent class constructor. Let's see a simple example:
super();
[Link]("dog is created");
class TestSuper3{
}}
Output:
animal is created
dog is created
Final Keyword In Java
The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can
be:
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.
There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed because
final variable once assigned a value can never be changed.
class Bike9{
[Link]();
}//end of class
class Bike{
public static void main(String args[]){ Honda honda= new Honda(); [Link]();
public static void main(String args[]){ Honda1 honda= new Honda1(); [Link]();
Ans) Yes, final method is inherited but you cannot override it. For Example:
class Bike{
new Honda2().run();
Output:running...
Q) What is blank or uninitialized final variable?
A final variable that is not initialized at the time of declaration is known as blank final variable.
If you want to create a variable that is initialized at the time of creating object and once initialized may not be changed,
it is useful. For example PAN CARD number of an employee.
class Student{
int id;
String name;
...
class Bike10{
Bike10(){ speedlimit=70;
[Link](speedlimit);
new Bike10();
Output: 70
Overriding Methods
Definition:
When a subclass (child class) defines a method with the same name, return type, and
parameters as a method in its superclass, the subclass’s version overrides the parent class
version.
This allows runtime polymorphism (method behavior changes depending on the object
type).
class Animal {
void sound() {
@Override
[Link]("Dog barks");
}
Final Variables, Methods, and Classes
Final Method
class Vehicle {
[Link]("Vehicle started");
}}
class Vehicle {
[Link]("Vehicle started");
}
Final Class
void draw() {
[Link]("Drawing...");
Finalizer Methods
Definition:
The finalize() method is called by the Garbage Collector before an object is destroyed to
perform cleanup operations (like closing files or freeing resources).
class Demo {
d1 = null;
A class declared with the keyword abstract is incomplete and cannot be instantiated
directly.
It can have abstract methods (without body) and concrete methods (with body).
Example:
[Link]("Sleeping...");
void sound() {
[Link]("Dog barks");
[Link]();
[Link]();
}}
Visibility Control in Java
Definition:
Visibility control in Java defines how accessible a class, variable, or method is from other
classes or packages.
This is achieved using Access Modifiers.
Access Modifiers:
package demo;
Key Points:
An array is a collection of elements of the same data type, stored in contiguous memory
locations.
One-Dimensional Array
�Example:
Output:
Mark 1: 90
Mark 2: 80
Mark 3: 70
Mark 4: 85
Mark 5: 95
Two-Dimensional Array
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
[Link]();
Output:
1 2 3
4 5 6
7 8 9
Strings in Java
Example:
String s1 = "Hello";
String s2 = new String("World");
Method Description
length() Returns string length
charAt(index) Returns character at position
toUpperCase() / toLowerCase() Converts case
concat() Joins two strings
equals() / equalsIgnoreCase() Compares strings
Vectors in Java
Example:
import [Link].*;
[Link]("Banana");
[Link]("Cherry");
[Link]("Banana");
Output:
Interfaces in Java
Definition:
An interface is a collection of abstract methods (and constants).
It defines what a class must do, but not how it does it.
Example:
interface Animal {
[Link]("Dog barks");
[Link]();
[Link]();
Output:
Dog barks
Dog eats food
interface InterfaceName {
// constant variables
// abstract methods
Example:
interface Animal {
Key Points:
Extending Interfaces
Just like classes, one interface can inherit another using the keyword extends.
This allows you to create hierarchies of interfaces.
Example:
interface Animal {
void eat();
}
interface Pet extends Animal {
void play();
[Link]();
[Link]();
Output:
A class implementing C must provide implementations for all methods from A, B, and C.
Implementing Interfaces
Example:
interface Vehicle {
void start();
void stop();
[Link]("Car started");
[Link]("Car stopped");
}
public class ImplementInterface {
[Link]();
[Link]();
Output:
Car started
Car stopped
Key Points:
public
static
final
Hence, they can be accessed without creating an object, using the interface name.
Example:
interface Constants {
int MIN = 1;
}
Output:
extends
One interface inherits interface B extends
Extending Interface A {}
another
Implementing implements
Class provides body for class C implements A
Interface interface methods {}
Accessing Interface Accessed using interface
— [Link]
Variables name
Unit IV PACKAGES, THREADS AND EXCEPTIONS
Packages in Java
1. Introduction
A package in Java is a namespace that organizes a set of related classes and interfaces.
Packages help to:
Types of Packages
User-defined Packages:
These are packages created by the programmer to group related classes.
Example:
import [Link];
class Example {
Examples:
[Link]
[Link]
[Link]
package [Link];
Creating a Package
You create a package using the package keyword at the top of your Java file.
Example:
package mypackage;
public class A {
Then compile:
javac -d . [Link]
The -d . flag tells the compiler to create the folder structure for the package.
Accessing a Package
import mypackage.A;
class B {
[Link]();
Using a Package
import mypackage.A;
class Test {
[Link]();
To add another class to the same package, simply include the same package statement.
Example:
package mypackage;
public class B {
import mypackage.*;
class Test {
[Link]();
[Link]();
Advantages of Packages
Creating Threads
In Java, there are two main ways to create threads:
[Link]("Thread is running...");
Note:
The run() method contains the code that represents the task to be performed by the
thread.
If extending Thread:
If implementing Runnable:
The thread enters the Runnable state and the JVM schedules it for execution.
The run() method executes independently of other threads.
Example
class MyThread extends Thread {
public void run() {
[Link]("Thread is running...");
}
}
This approach is preferred when you need to extend another class, since Java doesn’t
support multiple inheritance.
1. Introduction
In Java, a thread is a lightweight process that allows a program to perform multiple tasks
simultaneously.
Each thread goes through a life cycle — from its creation to its termination.
Java provides various methods in the Thread class to control and manage this life cycle.
2. Definition
The life cycle of a thread refers to the different states that a thread passes through during its
execution — from born (new) to dead (terminated).
Each thread in Java is represented by an object of the Thread class, which belongs to the
[Link] package.
State Description
2. Runnable (Ready to run) Thread is ready to run and waiting for CPU time.
4. Blocked / Waiting / Sleeping Thread is temporarily inactive (waiting for resource or sleep).
5. Terminated (Dead State) Thread has completed execution or stopped due to an error.
Thread is ready and waiting for the CPU scheduler to assign execution time.
Created by calling:
[Link]();
May enter the Running state when selected by the scheduler.
3. Running State
6. Example Program
class ThreadLifeCycle extends Thread {
public void run() {
[Link]("Thread is running...");
try {
[Link](1000); // moves to sleeping state
} catch (InterruptedException e) {
[Link](e);
}
[Link]("Thread is finished.");
}
try {
[Link](500); // main thread sleeps
[Link]("Thread state while running: " +
[Link]());
Sample Output:
Summary Points:
5. Synchronization in Java
When multiple threads access shared data, data inconsistency may occur.
Synchronization ensures that only one thread accesses the shared resource at a time.
class TestSynchronization {
public static void main(String args[]) {
Table obj = new Table();
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
[Link]();
[Link]();
}
}
Both threads use the same Table object, but synchronization ensures one thread executes the
method at a time.
6. Advantages of Multithreading
Method Description
Summary Table
Every thread in Java has a priority that helps the thread scheduler decide the order in
which threads are executed.
Thread priority is an integer value between 1 and 10.
�Example:
Note: Thread priority only suggests execution order — the final order depends on the thread
scheduler of the JVM.
2. Synchronization in Java
When multiple threads access shared data, data inconsistency may occur.
Synchronization ensures that only one thread can access a shared resource at a
time.
Types of Synchronization
1. Synchronized Method
2. Synchronized Block
class TestSync {
public static void main(String[] args) {
Table obj = new Table();
new MyThread1(obj).start();
new MyThread2(obj).start();
}
}
Syntax:
try {
// Code that may cause exception
} catch (ExceptionType e) {
// Handling code
} finally {
// Code that always executes
}
Example:
class ExceptionDemo {
public static void main(String[] args) {
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Division by zero not allowed.");
} finally {
[Link]("End of program.");
}
}
}
Example:
void checkAge(int age) throws ArithmeticException {
if (age < 18)
throw new ArithmeticException("Not eligible to vote");
else
[Link]("Eligible to vote");
}
Summary:
Exceptions in Java
1. Definition
An exception is an unwanted or unexpected event that occurs during the execution of a
program, which disrupts the normal flow of instructions.
Java uses exception handling to detect and handle these errors so that the program can
continue running smoothly.
Error Exception
4. Types of Exceptions
a) Checked Exceptions
Checked at compile-time.
Must be either handled or declared using throws.
Example: IOException, SQLException, FileNotFoundException.
b) Unchecked Exceptions
Occur at runtime.
Not checked at compile-time.
Example: ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException.
c) User-defined Exceptions
Keyword Description
6. Syntax Example
try {
int a = 10 / 0; // May cause exception
} catch (ArithmeticException e) {
[Link]("Division by zero not allowed!");
} finally {
[Link]("Program execution completed.");
}
Output:
1. Errors in Java
�Definition:
Errors are serious issues that occur due to system failure or resource limitations.
They are beyond the control of the programmer and usually cannot be recovered by the
program.
Types of Errors:
Example:
int a = 10 / 0; // Runtime error (ArithmeticException)
2. Exceptions in Java
�Definition:
An exception is an event that occurs during program execution and disrupts the normal
flow of instructions.
Exceptions can be handled by the program using Java’s exception handling mechanism.
Exception Hierarchy
Throwable
│
├── Error → (System level, cannot be handled)
└── Exception → (Application level, can be handled)
Types of Exceptions
Output:
Error Exception
Occurs due to serious system failure. Occurs due to faulty code or input.
Cannot be handled by the program. Can be handled using try-catch blocks.
Example: OutOfMemoryError Example: ArithmeticException
�Summary:
1. Introduction
In Java, exception handling is a mechanism to detect and manage runtime errors,
allowing the program to continue execution instead of crashing abruptly.
An exception is an unwanted event that disrupts the normal flow of a program.
Java provides a robust and object-oriented way of handling exceptions using the try,
catch, finally, throw, and throws keywords.
2. Definition
Exception Handling in Java is the process of responding to exceptions that occur during
program execution by taking appropriate actions, so that the program can continue running
normally.
4. Exception Hierarchy
Throwable
/ \
Exception Error
/ \
Checked Exception Unchecked Exception (Runtime)
Types of Exceptions:
Checked Checked at
IOException, SQLException, FileNotFoundException
Exceptions compile-time
Serious issues
Errors OutOfMemoryError, StackOverflowError
beyond control
Output:
Output:
Using throws:
Output:
import [Link].*;
class FileExample {
public static void main(String args[]) {
try {
FileReader fr = new FileReader("[Link]");
} catch (FileNotFoundException e) {
[Link]("File not found!");
} finally {
[Link]("File operation completed.");
}
}
}
Introduction
In Java, exception handling is a powerful mechanism that allows a program to handle runtime
errors and maintain normal program flow.
It is done using try, catch, finally, throw, and throws keywords.
A try block contains code that might throw an exception, and one or more catch blocks can
be used to handle different types of exceptions separately.
Definition
A Multiple Catch Statement in Java refers to using more than one catch block with a
single try block.
This allows the program to handle different types of exceptions in different ways
depending on the exception type that occurs.
Syntax
try {
// Code that may cause multiple exceptions
}
catch (ExceptionType1 e1) {
// Handling code for ExceptionType1
}
catch (ExceptionType2 e2) {
// Handling code for ExceptionType2
}
catch (Exception e) {
// General exception handler
}
Explanation
The try block encloses code that may generate one or more exceptions.
Each catch block handles a specific exception type.
When an exception occurs, the JVM searches for the first matching catch block
whose parameter matches the type of the thrown exception.
Once a suitable catch block is found, the control transfers to that block.
Only one catch block executes for a given exception.
Example Program
class MultipleCatchExample {
public static void main(String[] args) {
try {
int a = 10, b = 0;
int result = a / b; // may cause ArithmeticException
Output:
Arithmetic Error: Division by zero!
End of program execution.
How It Works
1. When an exception occurs inside the try block, control is immediately transferred to
the first matching catch block.
2. If the first catch block does not match the exception type, Java continues checking
the next one.
3. Once a suitable catch block is found, the rest of the catch blocks are skipped.
4. After executing the appropriate catch block, the program continues with the code after
the finally block.
Conclusion
Multiple Catch Statements in Java make exception handling more structured, readable, and
reliable.
They allow developers to handle various exceptions separately within the same program
block, improving error control and maintaining smooth program execution.