0% found this document useful (0 votes)
2 views27 pages

COS 201 Introduction To Java

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

COS 201 Introduction To Java

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

1

COS 201 (COMPUTER PROGRAMMING 1)


OBJECT-ORIENTED PROGRAMMING (OOP) IN JAVA

1. INTRODUCTION TO OOP
1.1 What is OOP?
Object-Oriented Programming (OOP) is a programming paradigm, a way of thinking about
programming, that focuses on designing software using “objects.”
i. An object is a self-contained unit that combines data (attributes) and behavior
(methods/functions).
ii. In simpler terms: an object is like a real-world entity. It has properties (characteristics)
and can-do things (actions).
1.2 Key Idea: Software as a Collection of Objects
Instead of writing step-by-step instructions like in procedural programming, OOP encourages
developers to model the software as a set of interacting objects, similar to how things interact in
real life.
Example (Analogy):
Think of a car:
i. Attributes (Data): color, brand, model, speed, fuel level
ii. Behaviors (Methods): start(), stop(), accelerate(), brake()
In OOP, we create a Car class as a blueprint, and each actual car (your friend’s car, your car, a
taxi) becomes an object created from that blueprint.
1.3 Why OOP?
OOP is not just a programming style; it solves real problems in software development. Here’s
why it’s important:
1. Model Real-World Systems
i. Many software systems represent real-world entities: banks, students, hospitals,
stores, vehicles.
ii. OOP lets us directly map real-world objects into code, making programs easier to
understand.
iii. Example: A student management system can have a Student class, a Course
class, and a Lecturer class—just like the real-world system.
2. Improve Modularity
i. Code is broken into self-contained units (classes/objects).
ii. Each object handles its own data and behavior, making programs organized and
manageable.
2

iii. Example: If we want to change how a Car accelerates, we only need to modify
the Car class, not the whole program.
3. Increase Code Reusability
i. Once a class is written, it can be reused to create many objects.
ii. Classes can also be extended to create new classes (inheritance).
iii. Example: A Vehicle class can be reused to create Car, Truck, and Bus
classes with minimal extra code.
4. Make Software Easier to Maintain
i. Because OOP organizes code into logical units, fixing bugs or adding features
becomes easier.
ii. Encapsulation ensures that internal details are hidden, reducing the chance of
breaking other parts of the program.
iii. Example: Changing the internal structure of the Student class doesn’t affect
code that uses Student objects if access is via getters/setters.
1.4 Real-Life Analogy of OOP
Real-World Entity OOP Concept
Car Class
Your Car Object
Color, Brand Attributes
Start(), Stop() Methods
Car blueprint Class Definition
Manufacturing multiple cars Object Instantiation

Think of a class as a recipe. The recipe defines ingredients and instructions (attributes and
methods). Each dish you cook from it is an object. You can make many dishes from the same
recipe.
Summarily,
i. OOP = designing programs using objects
ii. Object = combination of data (attributes) and behavior (methods)
iii. Key benefits: Real-world modeling, modularity, reusability, maintainability
iv. OOP is the foundation of Java, C++, C#, Python (partially), and many modern
programming languages.

1.2 WHY OOP IN JAVA?


3

Java is a programming language designed with Object-Oriented Programming at its core. Except
for primitive types like int, char, and boolean, everything in Java is treated as an object.
This makes Java ideal for teaching OOP concepts, building reusable software components, and
developing real-world applications.
1.2.1 Key Features and Advantages
1. Platform Independence – “Write Once, Run Anywhere”
i. Java programs are compiled into bytecode, which runs on the Java Virtual Machine
(JVM).
ii. This means the same program can run on Windows, Linux, or Mac without changes.
Example:
You write a Java program on Windows → compile → run it on MacOS
without modification.

Why it matters for OOP: Objects and classes you design in Java can be used across different
platforms seamlessly.

2. Automatic Memory Management (Garbage Collection)


i. Java automatically manages memory through Garbage Collection, which removes objects
that are no longer in use.
ii. This reduces memory leaks and makes software more reliable.
Analogy:
i. Imagine a library where books (objects) are automatically returned to shelves when no
one needs them, so no space is wasted.
ii. Why it matters for OOP: You can create and destroy objects freely without worrying
about manual memory management (unlike C++).

3. Large Standard Library


Java provides a rich set of pre-built classes (Java API) for:
i. File handling ([Link])
ii. Collections ([Link])
iii. Networking ([Link])
iv. GUI ([Link])
v. Data structures, math, threading, and more
Example:
4

ArrayList<String> names = new ArrayList<>();


[Link]("Amarachi");
[Link]("John");

You can focus on building objects and application logic instead of reinventing common features.

4. Strong Type Checking


i. Java enforces strict type rules at compile time, reducing runtime errors.
ii. Objects must be used according to their class definitions.
Example:
String name = "Chuks";
int age = 20;
name = age; // Compile-time error

Why it matters for OOP: Helps maintain data integrity within your objects and prevents misuse
of class attributes.

5. Widely Used in Industry


Java is used in:
i. Mobile applications – Android apps are written in Java/Kotlin
ii. Web applications – server-side applications using Spring, JSP, etc.
iii. Enterprise systems – banking, insurance, healthcare
iv. IoT and embedded systems – small devices and sensors
Implication for students:
i. Learning OOP in Java prepares them for real-world programming jobs.
ii. The concepts learned are transferable to other OOP languages like C++, C#, and Python.

Summarily,
a) Java = pure OOP language (except primitives)
b) Advantages for OOP:
i. Platform independence → code reuse across systems
ii. Automatic memory management → safer object creation
5

iii. Rich standard library → faster development


iv. Strong type checking → fewer bugs
v. Industry relevance → career-ready skills
Class Analogy:
Think of Java as a toolbox:
i. The tools (classes) are pre-built and standardized.
ii. You can combine them to build anything (applications) efficiently.
iii. Garbage collection ensures tools not in use are stored away, keeping your workspace
tidy.

2. KEY PRINCIPLES OF OBJECT-ORIENTED PROGRAMMING (OOP)


Object-Oriented Programming is built around four fundamental pillars. Understanding these
pillars is critical because they define how we design, structure, and use objects in software.
2.1 Encapsulation
Encapsulation is the process of hiding internal data of an object and providing controlled access
through methods, typically getters and setters.
i. Goal: Protect object data from unauthorized access or modification.
ii. Ensures data integrity and improves modularity.
Example
class Student {
private String name; // hidden data
private int age;

// getter
public String getName() {
return name;
}

// setter
public void setName(String name) {
[Link] = name;
}

public int getAge() {


return age;
}
6

public void setAge(int age) {


if (age > 0) {
[Link] = age;
}
}
}
i. Here, name and age are private; external code cannot access them directly.
ii. Access is controlled through getName(), setName(), etc.
Real-Life Analogy
Think of a capsule medicine:
i. Inside it is medicine (data)
ii. You cannot access it directly, only through instructions (methods) like swallowing.

2.2 Inheritance
Inheritance allows a class (child/subclass) to inherit attributes and methods from another class
(parent/superclass).
i. Promotes code reuse
ii. Enables hierarchical relationships
Example
class Vehicle {
String brand;
void start() {
[Link]("Vehicle started");
}
}

class Car extends Vehicle { // Car inherits from Vehicle


int doors;
void honk() {
[Link]("Car horn sounds!");
}
}
i. Car automatically has brand and start() from Vehicle
ii. Additional functionality (doors and honk()) is added specifically to Car.
Real-Life Analogy
i. Vehicle → Car, Truck, Bus
ii. All vehicles can move, start, stop, etc., but each has specific features.
7

2.3 Polymorphism
Polymorphism means “many forms.”
a) A single interface or method can behave differently depending on context.
b) Two common types in Java:
i. Method Overloading – same method name, different parameters
ii. Method Overriding – subclass changes behavior of a method from superclass
Example: Overloading
class Calculator {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
}
Example: Overriding
class Vehicle {
void start() {
[Link]("Vehicle started");
}
}

class Car extends Vehicle {


@Override
void start() {
[Link]("Car started with key");
}
}
Same method name start() behaves differently depending on the object type.
Real-Life Analogy
a) The word “open”:
i. Open a door → push/pull mechanism
ii. Open a file → double-click
iii. Open a bottle → twist cap
b) Same action name, different behavior depending on context.

2.4 Abstraction
Abstraction is the process of representing essential features of an object while hiding
unnecessary implementation details.
8

i. Focuses on what an object does, not how it does it


ii. Achieved in Java using abstract classes or interfaces
Example: Abstract Class
abstract class Shape {
abstract void draw(); // what to do
}

class Circle extends Shape {


void draw() {
[Link]("Drawing a Circle"); // how it is done
}
}
Shape defines what all shapes should do, but the actual implementation is in subclasses.
Real-Life Analogy
Driving a car:
i. You know how to steer, accelerate, brake (essential features)
ii. You don’t need to know how the engine works internally (hidden details)
In this module, we will focus on:
i. Classes & Objects – the building blocks of OOP
ii. Encapsulation – hiding data, controlling access
iii. Methods – defining object behavior
iv. Constructors – initializing objects
v. Method Overloading – a form of polymorphism
This gives students a practical foundation in OOP, enabling them to model real-world systems
efficiently using Java.

3. CLASSES AND OBJECTS


Object-Oriented Programming (OOP) revolves around classes and objects. They are the building
blocks of Java programs. Understanding them is critical to writing modular, reusable, and
maintainable code.

3.1 Class Definition


A class is like a blueprint or template for creating objects.
a) It defines:
9

i. Attributes (fields/variables) – the data or properties of the object


ii. Behaviours (methods/functions) – what the object can do
Analogy:
i. Think of a class as an architect’s blueprint for a house.
ii. The blueprint itself is not a house—it’s a plan.
iii. Using the blueprint, you can build many houses (objects) with the same design.

3.2 Syntax of a Class


class ClassName {
// fields (attributes)
// methods (behaviours)
}
a) class – keyword to define a class

b) ClassName – the name of the class (should start with a capital letter by convention)
c) Inside curly braces {}:
i. Fields – store object data
ii. Methods – define object behavior
3.3 Example: A Simple Student Class
class Student {
String name; // attribute
int age; // attribute
String department; // attribute

// method to display student information


void displayInfo() {
[Link]("Name: " + name);
[Link]("Age: " + age);
[Link]("Department: " + department);
}
}
Explanation:
i. String name, int age, String department → attributes storing student
details
ii. displayInfo() → method that prints the student’s information
iii. Methods can manipulate attributes or perform actions related to the object
10

Analogy:
i. Student class = plan for a student
ii. Attributes = student’s details
iii. Method = actions student can perform

3.4 Creating Objects


An object is an instance of a class.
i. You can create as many objects as you need from a class.
public class Main {
public static void main(String[] args) {
Student s1 = new Student(); // object creation

// Assign values to attributes


[Link] = "Amarachi";
[Link] = 19;
[Link] = "Computer Science";

// Call the method


[Link]();
}
}
Explanation:
1. Student s1 = new Student();
i. Student → class name
ii. s1 → object reference
iii. new Student() → allocates memory and creates the object
2. [Link] = "Amarachi";
i. Sets the name attribute of the object s1
3. [Link]();
i. Calls the object’s method to display information
Output:
Name: Amarachi
Age: 19
Department: Computer Science
11

3.5 Key Points


i. Class = blueprint; Object = actual instance
ii. Objects store their own data; multiple objects can exist from the same class
iii. Methods in the class define what each object can do
iv. Objects are created in memory using the new keyword

3.6 Real-Life Analogy


Concept Analogy
Class Blueprint of a house
Object A real house built from the blueprint
Attribute Color, size, number of rooms
Method Open door, turn on lights, lock windows

Figure 1: Class Object Relation


4. ENCAPSULATION
Encapsulation is one of the core principles of OOP. It ensures data security, controlled access,
and modular code.
4.1 What is Encapsulation?
12

Encapsulation means:
i. Wrapping data (attributes/fields) and methods (functions) inside a class
ii. Restricting direct access to the internal data
iii. Providing access only through controlled methods (getters and setters)
Key Idea:
i. The internal representation of an object is hidden from the outside.
ii. Only authorized methods can read or modify the data.
How to Achieve Encapsulation in Java
i. Declare fields as private – prevents external access
ii. Provide public getter and setter methods – allows controlled access
private int age; // hidden
public int getAge(){} // controlled access
public void setAge(int a){} // controlled modification

4.2 Example: Encapsulated Student Class


class Student {
private String name; // hidden from outside
private int age; // hidden from outside

// Getter for name


public String getName() {
return name;
}

// Setter for name


public void setName(String name) {
[Link] = name;
}

// Getter for age


public int getAge() {
return age;
}

// Setter for age with validation


public void setAge(int age) {
if(age > 0) { // prevent invalid data
[Link] = age;
13

}
}
}
Explanation:
i. private String name and private int age → these variables cannot be
accessed directly outside the class
ii. getName() and setName() → provide controlled access to name
iii. setAge()
→ includes validation to prevent invalid data (e.g., negative age)
Usage Example:
public class Main {
public static void main(String[] args) {
Student s = new Student();
[Link]("Amarachi"); // set name using setter
[Link](19); // set age using setter

[Link]("Name: " + [Link]());


[Link]("Age: " + [Link]());
}
}
Output:
Name: Amarachi
Age: 19

4.3 Why Encapsulation?


Encapsulation provides multiple benefits:
1. Protects data from invalid modification
i. Prevents external code from assigning incorrect values
ii. Example: negative age or empty name
2. Controls how variables are accessed
i. Access is only possible via getter/setter methods
ii. You can add validation logic in setters
3. Encourages modularity
i. Each class manages its own data
ii. Makes code easier to maintain and less prone to errors
14

Real-Life Analogy
1. Think of a capsule medicine:
i. Inside it is medicine (data)
ii. You cannot access the medicine directly; you only take it as instructed (methods)
2. This protects the medicine from misuse, just as encapsulation protects your object’s data.

5. METHODS
In Java, methods are the building blocks of behavior. They define what an object can do.
5.1 What is a Method?
A method is a block of code that performs a specific task.
i. Think of it as a function inside a class.
ii. Methods operate on objects or data, and they may return a result or perform an action.
Analogy:
1. A method is like a kitchen appliance:
i. Blender → mixes ingredients
ii. Toaster → toasts bread
2. You call the appliance to perform its action, just like you call a method in Java.

5.2 Types of Methods


1. Instance Methods
i. Require an object to be called
ii. Operate on object-specific data
iii. Example: [Link]()
2. Static Methods
i. Belong to the class itself, not an object
ii. Can be called using [Link]()
iii. Example: [Link](10, 20)
3. Accessor Methods (Getters)
15

i. Return the value of a private field


ii. Example: getAge()
4. Mutator Methods (Setters)
i. Modify the value of a private field
ii. Example: setAge(25)

5.3 Method Syntax


returnType methodName(parameterList) {
// body of the method
}

i. returnType → the type of value returned (void if nothing is returned)


ii. methodName → the name of the method
iii. parameterList → inputs the method needs (optional)
iv. body → code that performs the action

5.4 Example: Simple Method


public int add(int a, int b) {
return a + b;
}

Explanation:
i. public → access modifier (method can be called from anywhere)
ii. int → return type (method returns an integer)
iii. add → method name
iv. (int a, int b) → parameters (inputs)
v. return a + b; → performs addition and returns the result

Usage Example:
public class Calculator {
public int add(int a, int b) {
return a + b;
16

public static void main(String[] args) {


Calculator calc = new Calculator(); // create object
int sum = [Link](10, 20); // call instance
method
[Link]("Sum = " + sum);
}
}

Output:
Sum = 30

5.5 Key Points


i. Methods encapsulate actions within a class
ii. Instance methods depend on an object
iii. Static methods can be called without creating an object
iv. Getters and setters are specialized methods for accessing and modifying private data
v. Methods improve code reusability, readability, and modularity

6. CONSTRUCTORS
Constructors are special methods in Java designed to initialize objects when they are created.
6.1 What is a Constructor?
A constructor is a special type of method used to initialize the state of an object (i.e., assign
values to its attributes) when it is created.
Characteristics of Constructors
1. Same name as the class
i. Ensures the compiler recognizes it as a constructor
2. No return type
i. Unlike regular methods, constructors do not return any value, not even void
3. Called automatically
i. When an object is created using the new keyword, the constructor executes
automatically
17

Analogy
1) Think of a constructor as a factory machine that prepares a product:
i. The blueprint (class) exists
ii. When you press the “start” button (create an object), the machine automatically
sets up all initial components according to the blueprint
2) Example:
i. A Car class → constructor automatically sets color, model, and fuel level when a
new car object is created
6.2 Types of Constructors in Java
1. Default Constructor
i. Provided automatically by Java if you do not define any constructor
ii. Initializes object with default values
iii. Example: numeric fields → 0, boolean → false, objects → null
2. No-argument Constructor
i. Defined explicitly by the programmer
ii. Takes no parameters
iii. Example:
class Student {
String name;
int age;

// No-argument constructor
Student() {
name = "Unknown";
age = 0;
}
}

3. Parameterized Constructor
i. Defined explicitly with parameters to initialize attributes
ii. Example:
18

class Student {
String name;
int age;

// Parameterized constructor
Student(String n, int a) {
name = n;
age = a;
}
}

Usage Example:
public class Main {
public static void main(String[] args) {
// Using no-argument constructor
Student s1 = new Student();
[Link]([Link] + " - " + [Link]); // Output:
Unknown - 0

// Using parameterized constructor


Student s2 = new Student("Amarachi", 19);
[Link]([Link] + " - " + [Link]); // Output:
Amarachi - 19
}
}

Key Points About Constructors


i. Always named exactly as the class
ii. No return type
iii. Executed automatically during object creation
iv. Can be overloaded (like methods) to provide multiple ways to initialize objects
v. Ensures objects start in a valid state
7. METHOD OVERLOADING
Method overloading is a form of polymorphism in Java that allows multiple methods with the
same name but different signatures to coexist in a class.
7.1 What is Method Overloading?
Method overloading occurs when two or more methods in the same class have:
i. The same method name
19

ii. Different number of parameters or different parameter types


Key Idea:
i. It allows programmers to perform similar operations using the same method name,
improving readability and flexibility.
ii. Java determines which method to call at compile time based on the arguments provided.
Analogy
Think of the verb “add” in real life:
i. Add two numbers → add(10, 20)
ii. Add three numbers → add(10, 20, 30)
iii. Add decimal numbers → add(10.5, 20.5)
The action (“add”) is the same, but the inputs vary. This is exactly what method overloading
does in Java.
7.2 Example: Overloaded add Method
class Calculator {

// adds two integers


int add(int a, int b) {
return a + b;
}

// adds two doubles


double add(double a, double b) {
return a + b;
}

// adds three integers


int add(int a, int b, int c) {
return a + b + c;
}
}

Explanation
Method Signature What it does
add(int a, int b) Adds two integers
add(double a, double b) Adds two decimal numbers
add(int a, int b, int c) Adds three integers
20

Usage Example:
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();

[Link]([Link](10, 20)); // calls int


add(int, int)
[Link]([Link](10.5, 20.5)); // calls
double add(double, double)
[Link]([Link](1, 2, 3)); // calls int
add(int, int, int)
}
}

Output:
30
31.0
6

Key Points About Method Overloading


1. Same method name but different parameters
2. Can differ by:
i. Number of parameters
ii. Data types of parameters
3. Return type alone cannot differentiate methods
4. Compile-time polymorphism – the compiler decides which method to call
5. Improves code readability and maintains meaningful method names

Visual Analogy
Imagine a Swiss Army knife:
i. One tool name → “cut”
ii. Multiple blades → small blade, large blade, scissors
iii. Same action name, different ways of performing it
21

8. PUTTING IT ALL TOGETHER – PRACTICAL EXAMPLE


Let’s see how all the concepts we’ve learned—classes, objects, constructors, methods,
encapsulation—work together in a real-world scenario: a Bank Account system.

8.1 Bank Account Example


class BankAccount {
private String accountNumber; // encapsulated field
private double balance; // encapsulated field

// Constructor: initialize account


public BankAccount(String accNumber, double initialBalance) {
accountNumber = accNumber;
balance = initialBalance;
}

// Deposit method
public void deposit(double amount) {
balance += amount;
}

// Withdraw method
public void withdraw(double amount) {
if(amount <= balance) {
balance -= amount;
} else {
[Link]("Insufficient funds");
}
}

// Check balance
public double getBalance() {
return balance;
}
}

public class Main {


public static void main(String[] args) {
BankAccount b = new BankAccount("12345", 1000); // object
creation
[Link](500); //
deposit funds
22

[Link](300); //
withdraw funds
[Link]("Final Balance: " + [Link]());
}
}

Explanation
1. Encapsulation
i. accountNumber and balance are private fields
ii. They cannot be accessed directly outside the class
iii. Access is provided through methods (deposit, withdraw, getBalance)
2. Constructor
i. BankAccount(String accNumber, double initialBalance)
initializes the object automatically when created
3. Methods
i. deposit(double amount) → adds money to the balance
ii. withdraw(double amount) → subtracts money if sufficient funds are
available
iii. getBalance() → returns the current balance
4. Object Creation
i. BankAccount b = new BankAccount("12345", 1000);
ii. This creates an object of BankAccount with an account number and initial
balance
5. Performing Actions
i. [Link](500) → increases balance to 1500
ii. [Link](300) → decreases balance to 1200
iii. [Link]() → prints the final balance
Output:
Final Balance: 1200.0
23

Key Concepts Illustrated


Concept Example in Code
Class BankAccount

Object b

Constructor BankAccount(String accNumber, double initialBalance)

Encapsulation private accountNumber & private balance

Methods deposit(), withdraw(), getBalance()

Access Control Fields hidden, accessed via public methods

Real-Life Analogy
i. BankAccount class = blueprint for any bank account
ii. Object b = your personal bank account
iii. Deposit/Withdraw methods = teller transactions
iv. Encapsulation = your account balance is private; only the bank’s system (methods) can
update it

9. CLASSROOM EXERCISES – OBJECT-ORIENTED PROGRAMMING IN JAVA


These exercises are designed to reinforce the concepts of classes, objects, methods, constructors,
encapsulation, and method overloading.

Exercise 1: Create a Car Class


Requirements:
i. Attributes: brand, model, year
ii. Methods: displayInfo(), startEngine()
Hints/Guidelines:
class Car {
String brand;
String model;
int year;
24

// Method to display car information


void displayInfo() {
[Link]("Brand: " + brand);
[Link]("Model: " + model);
[Link]("Year: " + year);
}

// Method to simulate starting the engine


void startEngine() {
[Link](brand + " engine started.");
}
}

public class Main {


public static void main(String[] args) {
Car c1 = new Car();
[Link] = "Toyota";
[Link] = "Corolla";
[Link] = 2023;

[Link]();
[Link]();
}
}
Concepts Practiced: Classes, objects, methods, attributes

Exercise 2: Create a Rectangle Class


Requirements:
i. Use a parameterized constructor to initialize length and width
ii. Methods: area(), perimeter()
Hints/Guidelines:
class Rectangle {
double length;
double width;

// Parameterized constructor
Rectangle(double l, double w) {
length = l;
width = w;
}

// Method to calculate area


25

double area() {
return length * width;
}

// Method to calculate perimeter


double perimeter() {
return 2 * (length + width);
}
}

public class Main {


public static void main(String[] args) {
Rectangle r = new Rectangle(5, 3);
[Link]("Area: " + [Link]());
[Link]("Perimeter: " + [Link]());
}
}

Concepts Practiced: Constructors, methods, instance variables

Exercise 3: Method Overloading


Requirements:
Create a class MathOps with three overloaded multiply() methods
i. multiply(int a, int b)
ii. multiply(double a, double b)
iii. multiply(int a, int b, int c)
Hints/Guidelines:
class MathOps {

int multiply(int a, int b) {


return a * b;
}

double multiply(double a, double b) {


return a * b;
}

int multiply(int a, int b, int c) {


return a * b * c;
}
}
26

public class Main {


public static void main(String[] args) {
MathOps m = new MathOps();
[Link]([Link](2, 3));
[Link]([Link](2.5, 3.5));
[Link]([Link](2, 3, 4));
}
}

Concepts Practiced: Method overloading, polymorphism, code reuse


Exercise 4: Encapsulation
Requirements:
i. Create a Person class with private fields: name, age
ii. Provide getters and setters to access/modify fields
Hints/Guidelines:
class Person {
private String name;
private int age;

// Getter for name


public String getName() {
return name;
}

// Setter for name


public void setName(String name) {
[Link] = name;
}

// Getter for age


public int getAge() {
return age;
}

// Setter for age with validation


public void setAge(int age) {
if(age > 0) {
[Link] = age;
}
}
}
27

public class Main {


public static void main(String[] args) {
Person p = new Person();
[Link]("Amarachi");
[Link](19);

[Link]("Name: " + [Link]());


[Link]("Age: " + [Link]());
}
}

Concepts Practiced: Encapsulation, getters/setters, data protection, object initialization

10. SUMMARY OF SKILLS PRACTICED


Exercise Concepts Reinforced
1 Classes, objects, attributes, methods
2 Constructors, methods, instance variables
3 Method overloading, polymorphism
4 Encapsulation, getters/setters, data validation

You might also like