Chapter 1:
Introduction to Object-Oriented Programming (OOP)
Programming Paradigm
A programming paradigm is a style, approach, or way of thinking about how to write and
organize a program. It is a model or pattern for writing programs that guides how problems
should be solved using code. Think of programming paradigms as different cooking styles of egg
(fried, boiled, scrambled ). Each has its own techniques, ingredients, and presentation styles, but
all produce food.
Types of Programming Paradigms
1. Imperative Programming (How to achieve the goal)
A programmer tells the computer exactly how to do something through a series of explicit steps
Procedural(Structured) Programming: Based on functions or procedures
The program is divided into smaller steps (functions) that operate on data. How to solve the
problem (step by step)
Example: C, Fortran
Object-Oriented Programming (OOP): Based on objects and classes
Data and behavior are bundled together.
Models real-world entities. Who is responsible for what (objects)
Example: Java, C++, C#, Python.
2. Declarative Programming (What is the goal)
The programmer describes what the desired result is,
but doesn't necessarily specify the step-by-step control flow
Focuses on what needs to be achieved, not how
Functional Programming: Based on mathematical functions
Uses pure functions
Example: Haskell (also supported in JavaScript, Python, etc.)
Logic Programming: provides a set of facts and rules, and the computer finds the solution.
Example: Prolog. used for Artificial Intelligence, expert systems, and natural language
processing
Database Query Languages (SQL): Describe what data you want
Example: SQL: used to interact with and manage data stored in a relational database
Evolution of Programming Paradigms
1950s: Machine Code → Assembly
(Imperative thinking begins)
1960s: FORTRAN
(Procedural/Structured programming)
1970s: Pascal, C
(Structured programming refined)
1980s: C++
(Object-Oriented Programming emerges)
1990s: Java, Python, JavaScript
(OOP dominance, multi-paradigm languages)
2000s: C#,, Go
(Multi-paradigm, functional revival)
2010s: Rust, Kotlin
(Safe concurrency, modern multi-paradigm)
How to Choose a Paradigm?
Business applications → OOP
Data processing → Functional
AI/Expert systems → Logic
System programming → Procedural/Imperative
No single paradigm is "best" for all problems
Understanding multiple paradigms makes you a more versatile programmer
Most modern languages are multi-paradigm
1.1. Overview of OOP?
Object-Oriented Programming (OOP) is a programming paradigm that uses "objects" to
model real-world entities and their interactions. Unlike procedural programming, which
focuses on functions and sequences of actions, OOP organizes code around data (objects) and
the methods that operate on that data. Its primary goal is to increase modularity, reusability,
and maintainability of code.
Think about the world around you. You don't see 'functions' and 'procedures';
You see objects – cars, people, buildings, orders.
OOP brings this intuitive view into programming. Instead of a program being a long list of
instructions acting on data, the program becomes a collection of these self-contained 'objects'
that interact with each other. It allows us to represent real-world entities (like a Student, a
BankAccount, or a Car) directly in our code.
Easier to understand
More modular
More reusable
Easier to maintain and extend
Example: A Student → has attributes (name, ID, grade) and behaviors ( takeExam).
1.2. Why Java?
Java is a popular, general-purpose programming language, designed around OOP principles
Platform Independent ("Write Once, Run Anywhere")
Object-Oriented: Everything in Java is treated as an object
Strongly Typed: Reduces runtime errors by catching type mismatches at compile time.
Automatic Memory Management: The Garbage Collector handles memory, so you don't have
to manually manage pointers (like in C++).
Rich Standard Library: Provides extensive APIs for data structures, networking, and GUI
Multi-threading Support: Built-in support for concurrent programming
Community and Ecosystem: Large community, extensive documentation, and wide use in
enterprise, Android development, and web applications. It's trusted by large enterprises like
banks and tech companies.
History
Java was originally named Oak in 1991 by James Gosling for the "Green Team" project at
Sun Microsystems, named after an oak tree outside his office. It was renamed to Java in
1994-1995 because "Oak" was already trademarked by Oak Technologies. The final name
was inspired by coffee from Indonesia during a team brainstorming session.
Example HelloWorld
public class Sample {
public static void main(String[] args) {
System. [Link]("Hello, World!");
}
}
1.3. The JVM and Byte Code
How does Java run on any computer?
JVM (Java Virtual Machine): This is the "translator." It reads the Byte Code and executes it as
machine code on your specific OS.
Source Code (.java) -> Compiler (javac) -> Bytecode (.class) -> JVM (Windows/Linux/Mac) ->
Running Program
Compiler (javac): Translates your .java file into .class files containing bytecode.
Bytecode (.class): An intermediate, platform-independent code. It's not machine code. Bytecode is
like a universal language
Java Virtual Machine (JVM): The heart of the "Write Once, Run Anywhere" concept. It interprets and
executes the bytecode.
When you write any Java program, it does not run directly on the operating system like C or C++, but
runs through the JVM.
Java follows the famous principle “Write Once, Run Anywhere”. As a result, Java programs are
highly portable, secure, and reliable.
Each platform (Windows, macOS, Linux) has its own specific JVM.
The JVM acts as an abstraction layer, so your bytecode runs the same way on all of them.
References: [Link]
[Link]
Share: [Link]
Java Virtual Machine (JVM) is a core component of the Java Runtime Environment (JRE) that allows
Java programs to run on any platform without modification. JVM acts as an interpreter between Java
bytecode and the underlying hardware
Java source (.java) -> compiled by javac -> bytecode (.class)
JVM loads the bytecode, verifies it, links it, and then executes it
Execution may involve interpreting bytecode or using Just-In-Time (JIT) compilation to convert “hot”
code into native machine code for performance
Garbage collection runs in the background to reclaim memory from unused objects
Component: What It Is Purpose
JVM Java Virtual Machine executes bytecode
JRE Java Runtime Environment provides an environment to run Java programs
JDK Java Development Kit provides tools and libraries to develop Java apps
JIT Just-In-Time Compiler Bytecode to machine code at runtime to speed up execution
JDK: to write and compile .java to .class.
JRE: provides the environment (libraries) to run it.
JVM: executes the code.
JIT: makes the execution fast.
1.4. Basic concepts of OOP
1.4.1 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.
Think of a class as a design of a real-world entity.
Think of a class as a cookie cutter. The cookie cutter itself is not a cookie—it's just a shape. But once
you have that cutter, you can create as many cookies as you want, all with the same basic shape. In
programming, a class defines the 'shape' of our data and behavior.
Example:
class Person {
private String name; // Private variable
// Getter method
public String getName() {
return name;
}
// Setter method
public void setName(String name) {
[Link] = name;
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
[Link]("John"); // Set the name using setter
[Link]([Link]()); // Get the name using getter
}
}
1.4.2 Object
Object represents real-life entities. An object is an instance of a class. A physical entity. When you
use the new keyword, the JVM allocates memory for that specific object.
1.4.3 Members
Members are the components inside a class
Members define what an object has and does.
Variables (data members): Represent/Store the state or data of the object e.g., int speed.
Methods (member functions): Represent the behavior or actions the object e.g., accelerate()
1.4.4. class member visibility
Class Member Visibility (Access Modifiers) controls where members can be accessed.
Four Levels of Visibility
Modifier Accessible Same Subclass Everywhere
Within Class Package
private Yes No No No
default Yes Yes No No
(no
modifier)
protected Yes Yes Yes No
Public Yes Yes Yes Yes
1.4.5. encapsulation, inheritance, and polymorphism
The four pillars of OOP are Encapsulation, Inheritance, Polymorphism, and Abstraction.
1. Encapsulation: The Power of Hiding Data
What is 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 is like putting a lock on the box where your data is stored and only giving
access through a controlled key (getter and setter methods). It allows you to hide the internal
details of an object and only expose what is necessary to the outside world. This protects your
data from unauthorised access and changes.
In Java, encapsulation is achieved by making class variables private and providing public
getter and setter methods to access them.
2. Inheritance: Reusing Code for Better Design
Inheritance allows one class to inherit properties and behaviours from another class. It helps
avoid duplication of code by enabling a new class to reuse code from an existing class. In
Java, a subclass (child class) can inherit from a superclass (parent 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.
3. Polymorphism: One Method, Many Forms
Polymorphism means having many forms. Polymorphism allows objects of different
classes to be treated as objects of a common superclass. The specific method that gets called
is determined at runtime, depending on the object type. It means “many forms” and is mostly
achieved through method overriding and method overloading.
Method Overriding (Runtime Polymorphism): a subclass provides its own version of a
method already defined in the superclass.
Method Overloading (Compile-time Polymorphism): Achieved when multiple methods have
the same name but different parameters. The method call is resolved at compile time.
4. Abstraction: Hiding the Complexity
Abstraction is the concept of hiding the complex implementation details and showing only
the essential features. It allows you to focus on what an object does, rather than how it does
it.
In Java, abstraction is achieved using abstract classes and interfaces.
● 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 represents abstraction, where the user interacts with simple operations
while the internal working and implementation details remain hidden.
● Encapsulation helps in hiding the internal data of an object.
● Inheritance allows you to reuse code and create a hierarchy.
● Polymorphism provides flexibility by allowing objects to behave differently.
● Abstraction simplifies complex systems by showing only the essential features.
Procedure-Oriented Programming Language
Advantages
● Code reusability: Classes and objects allow the reuse of existing code, reducing
duplication and improving efficiency.
● Better structure and maintainability: Programs are organized into logical units,
making code easier to understand, debug, and maintain.
● Supports DRY principle: Common functionality is written once and reused,
leading to cleaner and more maintainable code.
● Faster development: Modular and reusable components help in quicker and more
scalable application development.
Disadvantages
● Steep learning curve: Concepts like classes, objects, inheritance, and
polymorphism can be difficult for beginners.
● Overhead for small programs: OOP may require more code and structure than
necessary for simple applications.
● Debugging complexity: Code spread across multiple classes and layers can make
debugging more time-consuming.
● Higher memory usage: Creating many objects can consume more memory
compared to procedural programs.
Chapter 2:The inside of objects and classes: More on OOP
concepts
Introduction
Hello World!
public class Main {
public static void main(String[] args) {
[Link]("Hello Java!");
}
}
Compile and Run java Program
Step 1: open the cmd.(command prompt) and go to the directory where you save
your HelloWorld program.
(Assume your file is save in below directory.
D:\java\[Link])
Step 2: Type ‘javac [Link]’ and enter to compile the code. If no error it
goes to next line.
Step 3: Type ‘java HelloWorld’ to run your HelloWorld program.
Now you will be able to see the output in command prompt.
When you run a Java program, the Java Virtual Machine (JVM) looks for this exact
method signature and executes it.
public
Access modifier public is accessible from anywhere b/c JVM needs to call this
method from outside the class. If you omit public, the JVM won’t find the entry point,
and you'll get a runtime error: Main method not public.
static
Indicates that the method belongs to the class itself, not to any particular instance
(object). When the program starts, no objects exist yet – the JVM cannot create an
object to call an instance method. By marking main as static, the JVM can invoke it
simply by using the class name (e.g., [Link](...)).
void
The return type. void means the method does not return any value to the caller (the
JVM). The main method completes and the program terminates; there is no
meaningful value to return.
main
The name of the method. This is the identifier the JVM looks for. It must be spelled
exactly main (case‑sensitive).
String[] args
A parameter that is an array of String objects. This array holds any command‑line
arguments passed to the program when it is [Link] can name the parameter
anything (e.g., String[] arguments), but the type must be String[] (or the varargs
equivalent String... args). If no arguments are given, the array is not null; it is an
empty array of length 0.
System
A final class in the [Link] package. It contains several useful static fields and
methods. You do not need to import it because [Link] is automatically imported.
out
A static field inside the System class of type PrintStream. It represents the standard
output stream (typically the console). Because it's static, you access it as
[Link].
println
A method of the PrintStream class. It prints the argument (here a String) to the
output stream and then terminates the line (moves the cursor to the next line).
overloaded versions for different data types (e.g., println(int), println(double), etc.).
[Link](...) sends the given text to the console followed by a newline.
print
prints the argument (here a String) to the output stream and doesn't add new line
[Link]
Important note: In Java, each statement must end with a semicolon (;) and it is
mandatory. Forgetting to add a semicolon will result in a compilation error. However,
note that code blocks enclosed in curly braces {} (like class and method
declarations) don't need semicolons.
Comments
Single-line comments: Use // to comment out a single line.
Multi-line comments: Use /* to start and */ to end a multi-line comment block.
public class Main {
public static void main(String[] args) {
// This is a single-line comment
[Link]("Hello, Coddy!"); // This is another single-line comment
/*
This is a multi-line comment.
It can span multiple lines.
*/
[Link]("Comments are useful for explaining code.");
}
}
Variables
A variable is like a memory unit that we can access by typing the name of the
variable.
Each variable has a unique name and a value that can be of different types. Java
has various built-in data types that define the type of value a variable can hold.
reserved keywords (e.g., class, public, static, void, if, else, for, while, etc.). You
cannot use them as identifiers (variable names, class names, etc.).
To initialize a variable, we use the following format:
variable_type variable_name = value;
Numbers
Numbers are typically represented using two main data types: int and double.
int is used to store whole numbers without any decimal point. double is used to store
numbers with a decimal point.
For example:
int age = 60;
double price = 99.99;
double pi = 3.14159;
String
A char is a single character (For example: 1, 6, %, b, p, ., T, etc.)
The String type is a special type that consists of multiple chars.
To initialize a string value in a variable, enclose it within double quotation marks:
String s1 = "This is a string";
Boolean
A Boolean type has only 2 possible values: true or false.
To assign a boolean value to a variable, use the keyword boolean followed by the
variable name:
boolean variable_true = true;
boolean variable_false = false;
Char
A char is a single character (For example: 1, 6, %, b, p, ., T, etc.)
The char type is a special type that consists of a single character.
To initialize a char value in a variable, enclose it within single quotation marks:
char c1 = 'h';
Type Declaration
Once a variable is declared with a certain type, it can only hold values of that type.
For instance, an int variable can only hold integer values, and a String variable can
only hold text.
For example:
int age = 25; // Can only hold whole numbers
String str = "abc"; // Can only hold text
These would cause errors:
age = "defg"; // Error: can't put text in an int variable
str = 25; // Error: can't put a number in a String variable
Constants
A constant is a special type of variable that cannot be changed once it is initialized.
To declare a constant use the keyword final followed by the variable type:
final int MAX_VALUE = 100;
MAX_VALUE = 200; // This will cause an error
result in an error because constant values cannot be changed.
Naming Conventions
Naming conventions to keep your code readable and maintainable. Here are some
key rules:
Variable Names: Use camelCase: Start with a lowercase letter, then capitalize the
first letter of each subsequent word (e.g., firstName, studentCount).
Choose descriptive names that indicate the variable's purpose (e.g., userAge instead
of ua).
Avoid single-letter names except for simple loop counters.
Constant Names: Use UPPER_SNAKE_CASE: Write in uppercase letters, with
words separated by underscores (e.g., MAX_VALUE, PI_VALUE).
Use for values that don't change throughout the program.
General Rules: Names can contain letters, digits, underscores, and dollar signs.
Names must start with a letter, an underscore _, or a dollar sign $.
Names are case-sensitive (myVariable is different from myvariable).
Avoid using Java's reserved keywords (like int, class, public, etc.).
Following these conventions helps make your code more understandable, especially
when working in teams or revisiting your code later.
Type Casting
Type casting is the process of converting a value from one data type to another.
In Java, we can convert integers to doubles, doubles to integers, and more. There
are two types of casting: implicit (automatic) and explicit (manual) casting.
For example integer to double:
Implicit (automatic) casting:
int number = 5;
double decimal = number; // automatically becomes 5.0
// with calculation
int x = 7;
double result = x / 2.0; // result is 3.5
Explicit (manual) Casting double to integer:
double decimal = 9.7;
int number = (int) decimal; // becomes 9 (decimal part is truncated)
// with calculation
double price = 19.99;
int roundedPrice = (int) price; // becomes 19
It is also possible to convert number and booleans to string and vice versa. To
convert a value to string we can use the [Link]() function:
int number1 = 789;
double number2 = 789;
boolean isValid = true;
String text1 = [Link](number1); // becomes "789"
String text2 = [Link](number2); // becomes "789.0"
String text3 = [Link](isValid); // becomes "true"
To convert a string to a different type is a bit more complicated:
String to Integer:
String numberText = "123";
int number = [Link](numberText); // becomes 123
String to Double:
String decimalText = "45.67";
double decimal = [Link](decimalText); // becomes 45.67
String to Boolean:
String boolText = "true";
boolean bool = [Link](boolText); // becomes true
parseBoolean will convert any case-insensitive string that has the value “true”. For
example True, tRue, TRUE will all become true
Trying to convert a string to an invalid type will result in an error:
String invalidNumber = "abc";
int number = [Link](invalidNumber); // This will cause a
NumberFormatException
Arithmetic Operators
Most basic arithmetic operators, they may be familiar from math classes.
Operator
Operation
Example
+
Addition
3+2=5
-
Subtraction
3-2=1
*
Multiplication
3*2=6
/
Division
4/2=2
Let's see usage example,
int a = 3;
int b = 5;
int c = a + b; // c holds 8
When working with decimal numbers in Java, we use the double data type, which
can store numbers with decimal points. The same arithmetic operators (+, -, *, /)
work with doubles just like they do with integers:
double x = 3.3;
double y = 4.1;
double z = x + y; // z holds 7.4
Modulo Operator
The modulo operator % gives the remainder of a division. In Java, it's used with a
simple syntax:
result = dividend % divisor;
Increment/Decrement
Increment and decrement operators are used to increase or decrease the value of a
variable by 1. These operators are widely used in programming, especially in loops
and counters.
The increment operator is represented by two plus signs ++, and the decrement
operator is represented by two minus signs --.
For example, to increment a variable named count, you can use the increment
operator like this:
int count = 5;
count++; // count is now 6
int value = 10;
value--; // value is now 9
Post Increment/Decrement
Increment (++) and Decrement (--) operators can be used in two ways:
Pre-increment/decrement (++x or --x):
The operator goes BEFORE the variable
The value changes IMMEDIATELY
The new value is used in the expression
int x = 5;
int y = ++x;
// x is increased to 6 first, then y becomes 6
Post-increment/decrement (x++ or x--):
The operator goes AFTER the variable
The original value is used first
The value changes AFTER the expression
int x = 5;
int y = x++;
// y becomes 5 first, then x increases to 6
Relational (Comparison) Operators
Operator Meaning Example
== Equal to a == b
!= Not equal to a != b
> Greater than a > b
< Less than a < b
>= Greater than or equal a >= b
<= Less than or equal a <= b
Logical Operators
Operator Meaning Example
&& Logical AND (a > 0) && (b < 10)
|| Logical OR (a > 0) || (b < 10)
! Logical NOT !(a > 0)
Control Flow
if-else
if (speed > 60) {
[Link]("Slow down!");
} else {
[Link]("Speed is fine.");
}
switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
default:
// code
}
for Loop
for (int i = 0; i < 5; i++) {
[Link]("class: " + i);
}
while (condition) {
// loop body
}
do {
// loop body
} while (condition);
2.1. member methods and their components
A member method (or instance method) belongs to an object of a class.
Components of a method:
Access modifier (e.g., public, private)
Return type (e.g., void, int, String)
Method name (e.g., calculateTotal)
Parameter list (zero or more parameters)
Method body (enclosed in {})
Example:
public class Calculator {
// Method
public int add(int a, int b) {
int sum = a + b;
return sum;
}
}
import [Link];
class DateApp {
public static void main (String args[]) {
Date today = new Date();
// three actions: declaration, instantiation, and initialization
[Link]("Today: " + today);
}
}
2.2. instantiation and initializing class objects
Declaring an Object
Either way, a declaration takes the form of
type name
Date today;
where type is either a simple data type, such as int, float, or boolean,
or a complex data type, such as a class like the Date class. name
Declarations simply notify the compiler that you will be using name
to refer to a variable whose type is type. Declarations do not instantiate objects.
Instantiating an Object
"new" operator instantiates a new object by allocating memory for it
new requires a single argument: a constructor method for the object to be created.
The constructor method is responsible for initializing the new object.
Initializing an Object
Classes provide constructor methods to initialize a new object of that type.
In a class declaration, constructors can be distinguished from other methods
because they have the same name as the class and have no return type.
For example
class Student {
int id;
String n;
public Student(int id, String n) {
[Link] = id;
this.n = n;
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student(10, "Abebe");
[Link]([Link]);
[Link](s1.n);
}
}
2.3. constructors
Constructor: Runs automatically when the object is created. It has the same name as
the class and no return type.
Example initializing object
Student s1 = new Student();
Student → class
s1 → reference variable
new → allocates memory
2.3.1. default and parameterized
A constructor that takes no arguments is known as the default constructor. Like Date,
most classes have at least one constructor, the default constructor. However, classes
can have multiple constructors, all with the same name but with a different number or
type of arguments.
For example, the Date class supports a constructor that requires three integers:
Date(int year, int month, int day)
Default Constructor
Provided automatically if no constructor is defined, or explicitly coded.
Has the same name as the class
Has no return type
class Car {
String model;
// Default constructor (implicitly provided)
}
class Hello{
// Default Constructor
Hello(){
[Link]("Default constructor");
}
public static void main(String[] args){
Hello hi = new Hello();
}
}
Note: It is not necessary to write a constructor for a class because the Java compiler
automatically creates a default constructor (a constructor with no arguments) if your
class doesn’t have any.
Parameterized Constructor
Allows to pass data, an object is created, and to initialize fields of the class with own
values, then use a parameterized constructor.
class Car {
String model;
int year;
// Parameterized constructor
Car(String m, int y) {
model = m;
year = y;
}
}
2.3.2. overloaded constructors
Having multiple constructors in the same class with different parameters.
This gives the user "options" on how to create the object.
class Rectangle {
double length, width;
// No-arg constructor
Rectangle() {
length = 1.0;
width = 1.0;
}
// Parameterized constructor
Rectangle(double l, double w) {
length = l;
width = w;
}
// Constructor with one parameter (square)
Rectangle(double side) {
length = side;
width = side;
}
}
2.4. methods
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. A method is a block of code that only runs when it is called.
Syntax of a Method
modifier return type name(parameters){
//body
}
Non-access Modifiers provide information about the behavior of the method to the
Java Virtual Machine (JVM). The modifier static means the method belongs to the
class, and it can be accessed without creating an object (an object is an instance of
a class).
public int add(int x, int y){
return x+y;
● Multi-word names should follow camelCase format.
Use Methods
● Methods help improve readability, reusability, Modularity, and maintainability
Types of Methods in Java
1. Predefined Method
method that is already defined in the Java class libraries. It is also known as the
standard library method or built-in method.
[Link]()
Example
Use import [Link].*;
[Link]() // returns random value
[Link] // return pi value
[Link](9.3333) // return round number
2. User-defined Method
method written by a programmer and modified according to the requirement.
Example:
public class Main {
public int add(int a, int b) {
return a + b;
public static void main(String[] args) {
int x = 7, y = 9;
Main m = new Main();
[Link]("add:" + [Link](x, y)); }
2.5. access specifiers
Control the visibility of classes, methods, and fields.
✅ ❌ ❌ ❌
Modifier Same Class Same Package Subclass (different package) Anywhere
✅ ✅ ❌ ❌
Private
(default)
✅ ✅ ✅ ❌
✅ ✅ ✅ ✅
protected
public
2.6. accessors and mutators
In oop usually make data private for safety, to interact with that data needs special
methods.
Accessor (Getter): "gets" or reads the value of a private variable.
Mutator (Setter): "sets" or updates the value of a private variable, often including
logic to make sure the data is valid.
public class Main {
private int age;
public int getAge() {
return age;
}
public void setAge(int a) {
[Link] = a;
}
public static void main(String[] args) {
[Link](23);
[Link]("Age: " + [Link]());
}
}
2.7. calling and returning methods
Calling Different Types of Methods in Java
Method calling in Java means invoking a method to execute the code it contains.
1. Calling a User-Defined Method
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,
4. Calling a Static Method
Static methods belong to the class, not the object. They can be called without
creating an object.
2.8. static and instance members
Different Ways to Create Java Method
1. Instance Method: Access the instance data using the object name. Declared
inside a class.
// Instance Method
void method_name() {
// instance method body
}
2. Static Method: Access the static data using class name. Declared inside class with
static keyword.
It belongs to the class rather than any specific object.
Can be called without creating an instance of the class.
Since static methods are not object-specific, they can access only static members
(data and methods), and cannot access non-static members.
// Static Method
static void method_name() {
// static method body
}
[Link]