Classes, Objects and Methods in
Java Programming
BSSE (I) – Ms Nazish Imran
OOPS
• OOP stands for Object-Oriented Programming.
• Procedural programming is about writing procedures or methods that
perform operations on the data, while object-oriented programming is
about creating objects that contain both data and methods.
• Object-Oriented Programming (OOP) is a programming paradigm based on
the concept of objects that contain data (fields) and behavior (methods). It
focuses on designing software that closely represents real-world entities. It
is used to:
• Improves code reusability
• Enhances maintainability and scalability
• Makes programs easier to understand and manage
• Closely models real-world entities
Characteristics of OOPS
Class
• Class
• A Class is a user-defined blueprint or prototype from which objects are
created. It represents the set of properties or methods that are common to
all objects of one type. Using classes, you can create multiple objects with
the same behavior instead of writing their code multiple times. In general,
class declarations can include these components in order:
• Modifiers: A class can be public or have default access (Refer to this for
details).
• Class name: The class name should begin with the initial letter capitalized
by convention.
• Body: The class body is surrounded by braces, { }.
Class
• Example: A Car represents a class (blueprint), while BMW, Mercedes,
and Audi represent objects (instances) created from that class.
Object
• Object
• An Object is a basic unit of Object-Oriented Programming that represents real-life
entities. A typical Java program creates many objects, which as you know, interact
by invoking methods. The objects are what perform your code, they are the part
of your code visible to the viewer/user. An object mainly consists of:
• State: It is represented by the attributes of an object. It also reflects the
properties of an object.
• Behavior: It is represented by the methods of an object. It also reflects the
response of an object to other objects.
• Identity: It is a unique name given to an object that enables it to interact with
other objects.
• Method: A method is a collection of statements that perform some specific task
and return the result to the caller.
Abstraction
• Abstraction
• Abstraction in Java is the process of hiding implementation details and
showing only the essential features of an object. It helps users focus on
what an object does rather than how it does it.
• Hides complexity: Internal implementation details are hidden from the
user.
• Improves maintainability: Changes in implementation do not affect the
user code.
• Enhances flexibility: Supports loose coupling through abstract classes and
interfaces.
• Example: An ATM or a coffee machine represents abstraction, where the
user interacts with simple operations while the internal working and
implementation details remain hidden.
Abstraction
Abstraction
• How to Achieve Abstraction
• It is achieved in Java using abstract classes and interfaces.
• Interfaces can provide 100% abstraction, while abstract classes
provide partial abstraction.
•
Encapsulation
• Encapsulation
• Encapsulation is the process of wrapping data and methods into a
single unit, usually a class, and restricting direct access to the data. It
acts as a protective shield that prevents data from being accessed
directly from outside the class.
• Data members are hidden using the private access modifier.
• Access to data is provided through public getter and setter methods.
• It improves data security, maintainability, and controlled access.
Encapsulation
Inheritance
• Inheritance
• Inheritance is a core OOP concept in Java that allows one class to
acquire the fields and methods of another class using the extends
keyword. It represents an “is-a” relationship between classes.
• The class being inherited is called the superclass, and the inheriting
class is the subclass.
• A subclass can use existing features of the superclass and also add its
own.
• Inheritance promotes code reusability and reduces redundancy.
• Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.
Inheritance
Inheritance
Inheritance
• Java supports the following types of inheritance:
• Single Inheritance: One subclass inherits from one superclass.
• Multilevel Inheritance: A class is derived from another derived class,
forming a chain.
• Hierarchical Inheritance: Multiple subclasses inherit from a single
superclass.
• Multiple Inheritance (through Interface): A class inherits from multiple
interfaces since Java does not support multiple inheritance using classes.
• Hybrid Inheritance (through Interface): A combination of two or more
types of inheritance, achievable using interfaces.
Polymorphism
• Polymorphism
• The word polymorphism means having many forms, and it comes
from the Greek words poly (many) and morph (forms), this means
one entity can take many forms. In Java, polymorphism allows the
same method or object to behave differently based on the context,
specially on the project's actual runtime class.
•
Polymorphism
Types of Polymorphism
• Types of Polymorphism
• Polymorphism in Java is mainly of 2 types as mentioned below:
• 1. Compile-time Polymorphism(Method Overloading) :Achieved
when multiple methods have the same name but different
parameters. The method call is resolved at compile time.
• 2. Runtime Polymorphism (Method Overriding ): Achieved when a
subclass provides a specific implementation of a method already
defined in its superclass. The method call is resolved at runtime based
on the object
• Objects share two characteristics: they all have state and behavior.
Dogs have state (name, color, breed, hungry) and behavior (barking,
fetching, wagging tail). Bicycles also have state (current gear, current
pedal cadence, current speed) and behavior (changing gear, changing
pedal cadence, applying brakes). Identifying the state and behavior
for real-world objects is a great way to begin thinking in terms of
object-oriented programming.
• Take a minute right now to observe the real-world objects that are in your
immediate area. For each object that you see, ask yourself two questions:
"What possible states can this object be in?" and "What possible behavior
can this object perform?". Make sure to write down your observations. As
you do, you'll notice that real-world objects vary in complexity; your
desktop lamp may have only two possible states (on and off) and two
possible behaviors (turn on, turn off), but your desktop radio might have
additional states (on, off, current volume, current station) and behavior
(turn on, turn off, increase volume, decrease volume, seek, scan, and tune).
You may also notice that some objects, in turn, will also contain other
objects. These real-world observations are a starting point to understand
the world of object-oriented programming.
• Software objects consist of state and related behavior. An object
stores its state in fields (variables in some programming languages)
and exposes its behavior through methods (functions in some
programming languages). Methods operate on an object's internal
state and serve as the primary mechanism for object-to-object
communication. Hiding internal state and requiring all interaction to
be performed through an object's methods is known as data
encapsulation — a fundamental principle of object-oriented
programming.
• Consider a bicycle, for example:
• By attributing state (current speed, current pedal cadence, and current gear) and providing methods for
changing that state, the object remains in control of how the outside world is allowed to use it. For example, if
the bicycle only has 6 gears, a method to change gears could reject any value that is less than 1 or greater than
6.
• Bundling code into individual software objects provides a number of benefits, including:
• Modularity: The source code for an object can be written and maintained independently of the source code for
other objects. Once created, an object can be easily passed around inside the system.
• Information-hiding: By interacting only with an object's methods, the details of its internal implementation
remain hidden from the outside world.
• Code re-use: If an object already exists (perhaps written by another software developer), you can use that
object in your program. This allows specialists to implement/test/debug complex, task-specific objects, which
you can then trust to run in your own code.
• Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it
from your application and plug in a different object as its replacement. This is analogous to fixing mechanical
problems in the real world. If a bolt breaks, you replace it, not the entire machine.
• In your applications, you will often find many individual objects all of
the same kind. There may be thousands of other bicycles in existence,
all of the same make and model. Each bicycle was built from the
same set of blueprints and therefore contains the same components.
In object-oriented terms, we say that your bicycle is an instance of
the class of objects known as bicycles. A class is the blueprint from
which individual objects are created.
• The following Bicycle class is one possible implementation of a
bicycle:
class Bicycle {
int cadence = 0;
int speed = 0;
int gear = 1;
void changeCadence(int newValue) {
cadence = newValue;
}
void changeGear(int newValue) {
gear = newValue;
}
void speedUp(int increment) {
speed = speed + increment;
}
void applyBrakes(int decrement) {
speed = speed - decrement;
}
void printStates() {
[Link]("cadence:" +
cadence + " speed:" +
speed + " gear:" + gear);
}
}
• The syntax of the Java programming language may look new to you, but the
design of this class is based on the previous discussion of bicycle objects.
The fields cadence, speed, and gear represent the object's state, and the
methods (changeCadence(), changeGear(), speedUp() etc.) define its
interaction with the outside world.
• You may have noticed that the Bicycle class does not contain
a main() method. That is because it is not a complete application; it is just
the blueprint for bicycles that might be used in an application. The
responsibility of creating and using new Bicycle objects belongs to some
other class in your application.
• Here is a BicycleDemo class that creates two separate Bicycle objects and
invokes their methods:
class BicycleDemo {
public static void main(String[] args) {
// Create two different
// Bicycle objects
Bicycle bike1 = new Bicycle();
Bicycle bike2 = new Bicycle();
// Invoke methods on
// those objects
[Link](50);
[Link](10);
[Link](2);
[Link]();
[Link](50);
[Link](10);
[Link](2);
[Link](40);
[Link](10);
[Link](3);
[Link]();
}
}
• The output of this test prints the ending pedal cadence, speed, and
gear for the two bicycles:
• cadence:50 speed:10 gear:2
• cadence:40 speed:20 gear:3
• Java Methods are blocks of code that perform a specific task. A
method allows us to reuse code, improving both efficiency and
organization. All methods in Java must belong to a class. Methods are
similar to functions and expose the behavior of objects.
• A method allows to write a piece of logic once and reuse it wherever
needed in the program.
• This helps keep your code clean, organized, easier to understand and
manage.
• Key Components of a Method Declaration
• Method consists of a modifier (Define access level), return type (what value returned or
void), name (Define the name of method follows camelCase), parameters (optional
inputs), and a body (Write your logic here).
• Why Use Methods?
• Breaking code into separate methods helps improve readability, reusability, and
maintainability
• Code Reusability: Write once, use multiple times without repeating code so that code
reusability increase.
• Modularity: Dividing a program into separate methods allows each method to handle a
specific task, making the code more organized and easier to manage.
• Readability: Smaller, named methods make the code easier to read and understand.
• Maintainability: It’s easier to fix bugs or update code when it's organized into methods.
• Method Call Stack in Java
• Java is an object-oriented and stack-based programming language
where methods play a key role in controlling the program's execution
flow. When a method is called, Java uses an internal structure known
as the call stack to manage execution, variables, and return
addresses.
• What is the Call Stack
• The call stack is a data structure used by the program during runtime
to manage method calls and local variables. It operates in a
Last-In-First-Out (LIFO) manner, meaning the last method called is the
first one to complete and exit.
• How Are Methods Executed
• When a method is called:
• A new stack frame is added to the call stack to store method details.
• The method runs its code.
• After execution, the stack frame is removed, and control goes back to
the calling method.
• Java automatically manages the call stack using the Java Virtual
Machine (JVM).
• Types of Methods in Java
• 1. Predefined Method
• Predefined methods are the method that is already defined in the Java class libraries. It is also known as the standard library
method or built-in method. For example, random() method which is present in the Math class and we can call it using
the [Link]() as shown in the below example.
• Example:
• [Link]() // returns random value
• [Link] // return pi value
• 2. User-defined Method
• The method written by the user or programmer is known as a user-defined method. These methods are modified according to
the requirement.
• Example:
• sayHello // user define method created above in the article
• Greet()
• setName()
• Different Ways to Create Java Method
• There are two ways to create a method in Java:
• 1. Instance Method: Access the instance data using the object name. Declared inside a class.
• Example:
• Loading Playground...
• // Instance Method
• void method_name() {
• // instance method body
• }
• 2. Static Method: Access the static data using class name. Declared inside class with static keyword.
• Example:
• Loading Playground...
• // Static Method
• static void method_name() {
• // static method body
• }
• Method Signature
• It consists of the method name and a parameter list.
• Number of parameters
• Type of the parameters
• Order of the parameters
• Note: The return type and exceptions are not considered as part of it.
• Method Signature of the above function:
• max(int x, int y) Number of parameters is 2, Type of parameter is int.
• Naming a Method
• In Java language method name is typically a single word that should be a verb in
lowercase or a multi-word, that begins with a verb in lowercase followed by an adjective,
noun. After the first word, the first letter of each word should be capitalized.
• Rules to Name a Method:
• Method names must start with a verb in lowercase.
• Multi-word names should follow camelCase format.
• Method names should be unique within a class unless method overloading is
allowed in Java.
• Calling Different Types of Methods in Java
• Method calling in Java means invoking a method to execute the code it contains.
It transfers control to the process, runs its logic, and then returns to the calling
point after execution.
• 1. Calling a User-Defined Method
• User-defined methods are blocks of code written by the programmer. To execute
a user-defined method, we first create an object of the class (if the method is
non-static) and then call the method using that object.
• 2. Calling an Abstract Method
• Abstract methods have no body and must be overridden in a
subclass. They are called using an object of the subclass.
• 3. Calling the Predefined Methods
• Java provides many built-in methods via the Java Standard Library,
like hashCode().
• 4. Calling a Static Method
• Static methods belong to the class, not the object. They can be called
without creating an object.
Difference Between Static Method and Instance
Method
• Access Modifiers in Java
• In Java, access modifiers are essential tools that define how the
members of a class, like variables, methods, and even the class itself,
can be accessed from other parts of our program.
• There are 4 types of access modifiers available in Java:
• Access Modifiers in Java
• Private Access Modifier
• The private access modifier is specified using the keyword
private. The methods or data members declared as private are
accessible only within the class in which they are declared.
• Default Access Modifier
• When no access modifier is specified for a class, method, or data member,
it is said to have the default access modifier by default. This means only
classes within the same package can access it.
• Protected Access Modifier
• The protected access modifier is specified using the keyword protected.
The methods or data members declared as protected are accessible within
the same package or subclasses in different packages.
• Public Access Modifier
• The public access modifier is specified using the keyword public. Public
members are accessible from everywhere in the program. There is no
restriction on the scope of public data members.