COMP 326/BBIT314/BMIS325/COMP226/COSF
311/INTE 222 – Object Oriented Programming (OOP) With Java
Lesson Four
Java Methods
Lecturer: Mercy Wairimu Gachoka
Outline
• Creating methods
• Method calling
• The void keyword
• Parameter passing
• Method overloading
• Constructors
• The this keyword
Lecturer: Mercy Wairimu Gachoka
Objects and classes-Definitions
-Objects with example
-Classes in Java
-creating objects
-Accessing instance variables and methods
-Simple case study
Lecturer: Mercy Wairimu Gachoka
Objects
Steps involved in creating objects in Java:
1. Define a Class
2. Instantiate the Class
3. Access Fields and Methods:
Lecturer: Mercy Wairimu Gachoka
Define a class
Declare the class using the class keyword.
Specify attributes (fields) and methods within the class
public class MyClass {
// Fields (attributes)
int myField;
String myString;
// Methods
void myMethod() {
// method implementation
}
}
Lecturer: Mercy Wairimu Gachoka
Instantiate the Class:
Use the new keyword to create an instance (object) of the class.
Assign the instance to a variable.
MyClass myObject = new MyClass();
Lecturer: Mercy Wairimu Gachoka
Example
Access Fields and // Define a simple class
class Car {
Methods: String model;
String color;
Use the dot (.) operator to access fields and
methods of the object.
void startEngine() {
// Accessing fields System.out.println("Engine started!");
myObject.myField = 42; }
System.out.println("Field value: " +
}
myObject.myField);
// Invoking methods // Instantiate the class to create objects
myObject.myMethod(); Car myCar = new Car();
myCar.model = "Toyota Camry";
myCar.color = "Blue";
In this example, a Car class is defined with fields for the model
// Accessing fields and methods
and color, and a method startEngine(). An object
System.out.println("My car model: " + myCar.model);
myCar is then created, and its fields are set and methods are
invoked using the dot notation. System.out.println("My car color: " + myCar.color);
myCar.startEngine();
Lecturer: Mercy Wairimu Gachoka
Objects
•Definition: Objects are instances of classes in object-oriented
•programming (OOP). They represent real-world entities and
•encapsulate data and behavior.
•Example: Consider a class Car. An object of this class could be a
•specific car instance, such as myCar. This object would have attributes
• like color, model, and methods like startEngine()
Lecturer: Mercy Wairimu Gachoka
Objects
•Definition: Objects are instances of classes in object-oriented
•programming (OOP). They represent real-world entities and
•encapsulate data and behavior.
•Example: Consider a class Car. An object of this class could be a
•specific car instance, such as myCar. This object would have attributes
• like color, model, and methods like startEngine()
Lecturer: Mercy Wairimu Gachoka
Objects with example
// Class definition
class Dog {
String name;
int age;
void bark() {
System.out.println("Woof!");
}
}
// Creating an object
Dog myDog = new Dog();
myDog.name = "Buddy";
myDog.age = 3;
// Accessing object's methods and attributes
System.out.println("My dog's name is " + myDog.name);
System.out.println("My dog is " + myDog.age + " years old.");
myDog.bark();
Lecturer: Mercy Wairimu Gachoka
Classes
•Definition: Classes are blueprints or templates for creating objects.
•They define the properties (attributes) and behaviors (methods) that objects
• instantiated from them will have.
•Example: In Java, a class for a Student could have attributes like name and age,
• and methods like study()
Lecturer: Mercy Wairimu Gachoka
Classes with example
// Class definition
class Rectangle {
double length;
double width;
double calculateArea() {
return length * width;
}
}
// Creating an object of the Rectangle class
Rectangle myRectangle = new Rectangle();
myRectangle.length = 5.0;
myRectangle.width = 3.0;
// Accessing the method and attributes of the object
double area = myRectangle.calculateArea();
System.out.println("Area of the rectangle: " + area); Lecturer: Mercy Wairimu Gachoka
Creating Objects
// Class definition
class Circle {
double radius;
double calculateArea() {
return Math.PI * radius * radius;
}
}
// Creating objects
Circle circle1 = new Circle();
circle1.radius = 2.5;
Circle circle2 = new Circle();
circle2.radius = 4.0;
// Accessing and displaying areas
System.out.println("Area of Circle 1: " + circle1.calculateArea());
System.out.println("Area of Circle 2: " + circle2.calculateArea());
Lecturer: Mercy Wairimu Gachoka
Accessing instance variables and methods
class Person {
String name;
int age;
void celebrateBirthday() {
age++;
System.out.println("Happy Birthday, " + name + "! You are now " + age + " years old.");
}
}
// Creating an object
Person person1 = new Person();
person1.name = "Alice";
person1.age = 25;
// Accessing instance variables and methods
System.out.println("Before birthday:");
System.out.println(person1.name + "'s age: " + person1.age);
person1.celebrateBirthday();
System.out.println("After birthday:");
System.out.println(person1.name + "'s age: " + person1.age);
Lecturer: Mercy Wairimu Gachoka
Simple Case Study
class BankAccount {
String accountHolder;
double balance;
void deposit(double amount) {
balance += amount;
System.out.println("Deposit of $" + amount + " successful. New balance: $" + balance);
}
void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
System.out.println("Withdrawal of $" + amount + " successful. New balance: $" + balance);
} else {
System.out.println("Insufficient funds. Withdrawal failed.");
}
}
}
// Creating an account and performing transactions
BankAccount myAccount = new BankAccount();
myAccount.accountHolder = "John Doe";
myAccount.balance = 1000.0;
myAccount.deposit(500.0);
myAccount.withdraw(200.0);
Lecturer: Mercy Wairimu Gachoka
myAccount.withdraw(900.0); // Insufficient funds example
Creating Methods
In Java, methods are blocks of code that perform a specific task and can
be defined within a class. Methods are declared using the following
syntax:
returnType methodName(parameter1Type parameter1Name, parameter2Type parameter2Name, ...) {
// method body
// code to perform a specific task
return returnValue; // optional return statement
}
Lecturer: Mercy Wairimu Gachoka
Creating Methods
Here's a breakdown of the components:
•returnType: The data type of the value that the method returns. Use void if the method does not return any value.
•methodName: The name of the method. This is the identifier you use to call the method.
•parameters: Input values that the method can accept. Parameters are optional, and a method may not have any.
•method body: The block of code enclosed in curly braces {} that defines what the method does.
•return statement: If the method returns a value, use the return keyword followed by the value to return.
Lecturer: Mercy Wairimu Gachoka
Method Calling
• Here's a breakdown of the
Syntax
components:
• // For calling a method within the same class
• methodName: The name of the
• methodName(argument1, argument2, ...);
method you want to call.
• argument1, argument2, ...: The
• // For calling a method from another class (assuming it's a static method) values you want to pass to the
• ClassName.methodName(argument1, argument2, ...); method (if it takes any
parameters).
• // For calling a non-static method from another class (after creating an
object)
• ClassName: The name of the class
• ClassName objectName = new ClassName();
where the method is defined.
• objectName.methodName(argument1, argument2, ...); • objectName: The name of the
object (if the method is non-static
and not in the same class).
Lecturer: Mercy Wairimu Gachoka
Calling a method within the same class:
class MyClass {
void myMethod() {
// Method body
}
public static void main(String[] args) {
// Calling myMethod within the same class
myMethod();
}
}
Lecturer: Mercy Wairimu Gachoka
Calling a static method from another class:
class AnotherClass {
static void staticMethod() {
// Method body
}
}
public class MainClass {
public static void main(String[] args) {
// Calling staticMethod from AnotherClass
AnotherClass.staticMethod();
}
}
Lecturer: Mercy Wairimu Gachoka
Calling a non-static method from another
class:
class AnotherClass {
void nonStaticMethod() {
// Method body
}
}
public class MainClass {
public static void main(String[] args) {
// Creating an object of AnotherClass
AnotherClass obj = new AnotherClass();
// Calling nonStaticMethod through the object
obj.nonStaticMethod();
}
}
Lecturer: Mercy Wairimu Gachoka
Creating Methods Example
public class Example {
// Method without parameters and without a return value
public static void sayHello() {
System.out.println("Hello, World!");
• sayHello is a method without parameters and without a return value
} (void). It simply prints a message.
• add is a method with two parameters (num1 and num2) and a return value
(int). It calculates the sum of the two numbers and returns the result.
// Method with parameters and a return value
• In the main method, we call both sayHello and add methods to
public static int add(int num1, int num2) { demonstrate their usage.
int sum = num1 + num2;
return sum;
}
public static void main(String[] args) {
// Calling the sayHello method
sayHello();
// Calling the add method
int result = add(5, 3);
System.out.println("Sum: " + result);
}
}
Lecturer: Mercy Wairimu Gachoka
Creating methods
class Book {
String title; public class BookMain {
String author; public static void main(String[] args) {
int pages; // Creating a Book object
Book book1 = new Book();
// Method to set book details
// Using the setDetails method to set values
public void setDetails(String bookTitle, String bookAuthor, int book1.setDetails("The Great Gatsby", "F. Scott Fitzgerald", 180);
bookPages) {
title = bookTitle;
// Using the displayDetails method to display book details
author = bookAuthor; book1.displayDetails();
pages = bookPages; }
} }
// Method to display book details
In this version:
public void displayDetails() { The Book class remains the same with its methods for setting details and displaying
them.
System.out.println("Book Details:");
The BookMain class contains the main method, where a Book object (book1) is
System.out.println("Title: " + title); created and its methods are invoked to set values and display details.
This separation adheres to the principle of encapsulation, where the Book class is
System.out.println("Author: " + author); responsible for its internal functionality, and the BookMain class demonstrates how
to use it.
System.out.println("Pages: " + pages);
}
} Lecturer: Mercy Wairimu Gachoka
Method Calling
• Here's a breakdown of the
Syntax
components:
• // For calling a method within the same class
• methodName: The name of the
• methodName(argument1, argument2, ...);
method you want to call.
• argument1, argument2, ...: The
• // For calling a method from another class (assuming it's a static method) values you want to pass to the
• ClassName.methodName(argument1, argument2, ...); method (if it takes any
parameters).
• // For calling a non-static method from another class (after creating an
object)
• ClassName: The name of the class
• ClassName objectName = new ClassName();
where the method is defined.
• objectName.methodName(argument1, argument2, ...); • objectName: The name of the
object (if the method is non-static
and not in the same class).
Lecturer: Mercy Wairimu Gachoka
Calling a method within the same class:
class MyClass {
void myMethod() {
// Method body
}
public static void main(String[] args) {
// Calling myMethod within the same class
myMethod();
}
}
Lecturer: Mercy Wairimu Gachoka
Calling a static method from another class:
class AnotherClass {
static void staticMethod() {
// Method body
}
}
public class MainClass {
public static void main(String[] args) {
// Calling staticMethod from AnotherClass
AnotherClass.staticMethod();
}
}
Lecturer: Mercy Wairimu Gachoka
Calling a non-static method from another class:
class AnotherClass {
void nonStaticMethod() {
// Method body
}
}
public class MainClass {
public static void main(String[] args) {
// Creating an object of AnotherClass
AnotherClass obj = new AnotherClass();
// Calling nonStaticMethod through the object
obj.nonStaticMethod();
}
}
Lecturer: Mercy Wairimu Gachoka
The void keyword
In Java, the void keyword is used as the public void methodName(parameter1Type
return type of a method to indicate that the parameter1Name, parameter2Type
method does not return any value. parameter2Name, ...) {
When a method's return type is void, it means // Method body
that the method performs a task or action but // Code to perform a specific task or action
does not produce a result that needs to be
returned or used by the calling code. // No return statement or return value is expected
Here's the basic syntax for a method with void }
return type:
Lecturer: Mercy Wairimu Gachoka
Here's an example to illustrate the use of void:
public class Example {
// Method with void return type In this example, the printMessage method takes a
public void printMessage(String message) { String parameter and prints a message to the
console.
System.out.println("Message: " + message);
The method is declared with void because it doesn't
} return any value to the caller.
Remember that when a method has a void return
public static void main(String[] args) { type, you don't use the return keyword with a value
// Creating an instance of the Example class
inside the method body.
Example example = new Example(); Instead, you simply perform the desired actions or
tasks within the method.
// Calling the method with void return type
example.printMessage("Hello, World!");
}
}
Lecturer: Mercy Wairimu Gachoka
Parameter Passing
•
Parameter passing in Java refers to the process of supplying values to
a method so that it can use those values to perform a specific task.
• Parameters allow you to make your methods more flexible and
reusable by accepting input data.
• There are two types of parameter passing in Java: pass-by-value and
pass-by-reference.
Lecturer: Mercy Wairimu Gachoka
public class PassByValueExample {
1. Pass-by-Value: public static void main(String[] args) {
int x = 10;
// Calling the method with a primitive parameter
• In Java, when you pass a primitive data type (like int, modifyValue(x);
double, char, etc.) to a method, you are passing its value.
• Any changes made to the parameter within the method
do not affect the original value outside the method. // The value of x remains unchanged after the method call
System.out.println("Value of x after method call: " + x);
}
// Method to modify a primitive parameter (pass-by-value)
public static void modifyValue(int value) {
value = 20;
System.out.println("Value inside method: " + value);
}
}
Output:
Value inside method: 20
Value of x after method call: 10
Lecturer: Mercy Wairimu Gachoka
public class PassByReferenceDemo {
2. Pass-by-reference: public static void main(String[] args) {
// Creating an object
Person person = new Person("John");
// Calling the method with an object parameter
class Person { modifyObject(person);
String name;
// The object's state is changed after the method call
public Person(String name) { System.out.println("Person after method call: " + person);
this.name = name; }
}
@Override // Method to modify an object parameter
public String toString() { public static void modifyObject(Person person) {
return "Person{" + // Modifying the state of the object
"name='" + name + '\'' + person.name = "Jane";
'}'; System.out.println("Person inside method: " + person);
} }
} }
Output:
Person inside method: Person{name='Jane'}
Person after method call: Person{name='Jane'}
Lecturer: Mercy Wairimu Gachoka
Pass by Reference
• In this example, the Person class Output:
has a name attribute, and the Person inside method:
PassByReferenceDemo class Person{name='Jane'}
creates a Person object named
"John". Person after method call:
Person{name='Jane'}
• The modifyObject method is
then called, and the name
attribute of the Person object is
modified directly without using
getters or setters.
Lecturer: Mercy Wairimu Gachoka
Difference between static and instance methods
The main differences between static and instance methods in Java are related to their behavior and how they are associated with
the class
and its instances:
1.Associated with the Class and Instance:
•Static Method: Belongs to the class rather than an instance of the class. It can be called using the class name directly,
without creating
• an object of the class.
•Instance Method: Belongs to an instance of the class. It is associated with the object and requires an instance of the class to
be called.
2.Accessing Instance Variables:
•Static Method: Cannot directly access instance variables. It operates on class-level data and does not have access to the
this reference.
•Instance Method: Can directly access instance variables and use the this reference to refer to the current object.
3.Accessing Static Variables:
•Static Method: Can directly access static variables (class-level variables).
•Instance Method: Can access both static and instance variables.
4.Usage of 'this' Keyword:
•Static Method: Cannot use the this keyword because there is no instance associated with it.
•Instance Method: Can use the this keyword to refer to the current object.
5.Invoking the Method:
•Static Method: Invoked using the class name (e.g., ClassName.methodName()).
•Instance Method: Invoked using an instance of the class (e.g., object.methodName()).
6.Memory Allocation:
•Static Method: Exists in memory once, associated with the class itself.
•Instance Method: Exists in memory for each instance of the class.
Lecturer: Mercy Wairimu Gachoka
Difference between static and instance methods
public class Example {
// Static method
public static void staticMethod() {
System.out.println("This is a static method.");
}
public static void main(String[] args) {
// Calling the static method using the class name
Example.staticMethod();
// Alternatively, you can call it using an object reference (not recommended)
Example obj = new Example();
obj.staticMethod();
}
}
Lecturer: Mercy Wairimu Gachoka
Difference between static and instance methods
public class Example {
static int staticVar = 10;
int instanceVar = 20;
// Static method
static void staticMethod() {
• In summary, static methods are
System.out.println("Static Method: " + staticVar);
// Cannot use 'this' in a static method
associated with the class itself
// System.out.println("Instance Var in Static Method: " +
this.instanceVar); // Error
and cannot access instance-
}
specific information directly,
// Instance method
void instanceMethod() { while instance methods are
System.out.println("Instance Method: " + instanceVar);
System.out.println("Static Var in Instance Method: " + staticVar); associated with instances of the
}
class and can access both static
public static void main(String[] args) {
// Calling static method
staticMethod();
and instance-specific
// Creating an instance
information.
Example exampleObj = new Example();
// Calling instance method
exampleObj.instanceMethod();
}
}
Lecturer: Mercy Wairimu Gachoka
Instance variables vs. static variables
• Associated with Instances and the Class:
Instance Variables: Belong to instances (objects) of a class. Each object has its own copy of instance variables, and changes to one instance variable do
not affect others.
Static Variables: Belong to the class itself rather than instances. There is only one copy of a static variable shared among all instances of the class.
• Memory Allocation:
Instance Variables: Each instance of the class gets its own memory space for instance variables. Changes to one instance's variables do not affect others.
Static Variables: Exist in a single memory location shared by all instances of the class. Changes to a static variable affect all instances.
• Usage and Access:
Instance Variables: Used to store unique characteristics for each instance of the class. Accessed using an object of the class.
Static Variables: Used to store data shared among all instances of the class. Accessed using the class name rather than an object.
• Initialization:
Instance Variables: Initialized separately for each object during object creation or using constructors.
Static Variables: Initialized when the class is loaded, usually at the time of the first instantiation or explicitly in a static block.
• Modifiability:
Instance Variables: Can have different values for each instance of the class. Modifiable independently for each object.
Static Variables: Have the same value for all instances of the class. Modifications are reflected across all instances.
• Lifetime:
Instance Variables: Live as long as the instance of the class exists. They are created when an object is instantiated and destroyed when the object is
garbage-collected.
Static Variables: Live as long as the class is loaded in memory. They are created when the class is loaded and destroyed when the class is unloaded.
Lecturer: Mercy Wairimu Gachoka
Instance variables vs. static variables
public class Example {
int instanceVar; // Instance variable In this example, instanceVar is an instance
static int staticVar; // Static variable variable, and staticVar is a static variable. Each
object (obj1 and obj2) has its own copy of
instanceVar, while there is only one shared copy
public Example(int value) { // Constructor to initialize instance variable of staticVar for all instances of the Example
this.instanceVar = value; class.
} Output:
Instance Variable in obj1: 10
public static void main(String[] args) {
Instance Variable in obj2: 20
// Creating instances of Example class
Static Variable: 5
Example obj1 = new Example(10);
Example obj2 = new Example(20);
Explanation
• Two instances of the Example class are
// Accessing instance variables
created (obj1 and obj2).
System.out.println("Instance Variable in obj1: " + obj1.instanceVar); • Each instance has its own instanceVar with
values 10 and 20, respectively.
System.out.println("Instance Variable in obj2: " + obj2.instanceVar);
• The static variable staticVar is modified to 5,
affecting all instances of the class.
Example.staticVar = 5; // Modifying static variable
• The values of the instance variables and the
// Accessing static variable
static variable are printed.
System.out.println("Static Variable: " + Example.staticVar);
}
} Lecturer: Mercy Wairimu Gachoka
Method Overloading
• Method overloading in Java allows you to define multiple methods in
the same class with the same name but with different parameter lists.
• The methods must have different parameter types or a different
number of parameters.
• The return type alone is not sufficient to distinguish overloaded
methods.
Lecturer: Mercy Wairimu Gachoka
Method Overloading
• Method overloading in Java allows you to define multiple methods in
the same class with the same name but with different parameter lists.
• The methods must have different parameter types or a different
number of parameters.
• The return type alone is not sufficient to distinguish overloaded
methods.
Lecturer: Mercy Wairimu Gachoka
Method Overloading
public class CalculatorMain {
class Calculator {
public static void main(String[] args) {
// Method to add two integers
Calculator calculator = new Calculator();
public int add(int num1, int num2) {
return num1 + num2;
// Calling different overloaded methods
}
System.out.println("Sum of two integers: " + calculator.add(5, 3));
System.out.println("Sum of three integers: " + calculator.add(5, 3, 7));
// Method to add three integers
System.out.println("Sum of two doubles: " + calculator.add(2.5, 3.7));
public int add(int num1, int num2, int num3) {
System.out.println("Concatenation of two strings: " + calculator.add("Hello",
return num1 + num2 + num3; " World"));
} }
}
// Method to add two doubles
public double add(double num1, double num2) {
return num1 + num2;
}
// Method to concatenate two strings
public String add(String str1, String str2) {
return str1 + str2;
}
}
Lecturer: Mercy Wairimu Gachoka
Method Overloading
Sum of two integers: 8
In this version: Sum of three integers: 15
• The Calculator class contains Sum of two doubles: 6.2
Concatenation of two strings: Hello World
only the method overloading
logic.
• Each line corresponds to the result of calling a different overloaded method
• The CalculatorMain class has the •
in the Calculator class.
The specific method called depends on the number and types of arguments
main method and creates an provided in each invocation.
instance of the Calculator class
to call its overloaded methods.
• This separation adheres to the
principle of organizing code into
classes, each with a specific
responsibility.
Lecturer: Mercy Wairimu Gachoka
Exercise: Calculator Overloading
1. Create a class named Calculator with the following methods:
• add method that takes two integers and returns their sum.
• add method that takes three integers and returns their sum.
• multiply method that takes two doubles and returns their product.
• multiply method that takes three doubles and returns their product.
• concatenate method that takes two strings and returns their concatenation.
2. Implement method overloading for the add, multiply, and concatenate methods.
3. Create an application class (CalculatorApp) with the main method to demonstrate the usage of the Calculator class:
• Create an instance of the Calculator class.
• Use both the two-argument and three-argument versions of the add and multiply methods.
• Use the concatenate method with strings.
• Display the results.
Lecturer: Mercy Wairimu Gachoka
Skeletal structure to get you started
// CalculatorApp.java
// Calculator.java
public class CalculatorApp {
public class Calculator {
public static void main(String[] args) {
// Method to add two integers
// Create a Calculator instance
public int add(int num1, int num2) {
// TODO: Instantiate a Calculator object
// TODO: Implement the method
return 0; // Placeholder return value
// Use the add and multiply methods with different arguments
}
// TODO: Call the methods and display the results
// Method to add three integers (overloaded)
// Use the concatenate method with strings
// TODO: Implement the method
// TODO: Call the method and display the result
}
// Method to multiply two doubles
}
// TODO: Implement the method
Instructions for Students:
• Complete the Calculator class by implementing method overloading
// Method to multiply three doubles (overloaded) for add, multiply, and concatenate.
// TODO: Implement the method • In the CalculatorApp class, create a Calculator object and use different
versions of the methods to perform calculations.
• Display the results to ensure that method overloading works as
// Method to concatenate two strings expected.
// TODO: Implement the method • This exercise provides practice in method overloading, allowing
students to understand how to define multiple methods with the
} same name but different parameter lists.
Lecturer: Mercy Wairimu Gachoka
Java Constructors
• In Java, constructors are special methods used to initialize objects.
• They are called when an object is created using the new keyword.
• Constructors have the same name as the class and can have
parameters or no parameters.
Lecturer: Mercy Wairimu Gachoka
Default contructors
public class ClassName {
// Default constructor with no parameters
public ClassName() {
// Constructor body
// Initialization code
}
}
Type: Data: The data type of each parameter.
Lecturer: Mercy Wairimu Gachoka
Parameterized Constructor:
public class ClassName {
// Parameterized constructor with parameters
public ClassName(Type parameter1, Type parameter2, ...) {
// Constructor body
// Initialization code based on parameters
}
}
Lecturer: Mercy Wairimu Gachoka
An example using Class: Person
In the example above:
public class Person {
• The Person class has a default constructor with no parameters and a
String name; parameterized constructor that takes name and age as parameters.
int age; • The this keyword is used to refer to the instance variables of the current
object.
• The constructor body contains initialization code that sets up the initial state
// Default constructor of the object.
public Person() { • When an object is created using the new keyword, the appropriate
constructor is called based on the arguments provided, initializing the
object's state.
// Constructor body
// Default initialization or setup
}
// Parameterized constructor
public Person(String name, int age) {
// Constructor body
// Initialization based on parameters
this.name = name;
this.age = age;
}
}
Lecturer: Mercy Wairimu Gachoka
The this keyword
• The this keyword in Java is a reference variable that refers to the
current object.
• It can be used to differentiate instance variables from local variables
when they have the same name.
• Additionally, this is often used to invoke current object's methods and
constructors.
Lecturer: Mercy Wairimu Gachoka
The this keyword
public class MyClass {
Referencing Instance Variables: private int value;
If a method has a parameter with the same
name as an instance variable, using this can // Constructor with a parameter having the
help distinguish between the two: same name as an instance variable
public MyClass(int value) {
// Using this to refer to the instance
variable
this.value = value;
}
}
In this example, this.value refers to the instance
variable value, while value refers to the
parameter.
Lecturer: Mercy Wairimu Gachoka
The this keyword
Referencing Instance Variables:
Consider a Book class representing a book with a title. When a method has a
parameter with the same name as an instance variable, using this can help // MainApp.java
distinguish between the two:
public class MainApp {
public static void main(String[] args) {
// Book.java
// Creating a Book object using the constructor
public class Book {
Book myBook = new Book("Java Programming");
private String title;
// Updating the title using the method
// Constructor with a parameter having the same name as an instance variable
myBook.updateTitle("New Java Programming");
public Book(String title) {
}
// Using this to distinguish between instance variable and parameter
}
this.title = title;
}
// Method to update the title
public void updateTitle(String title) {
// Using this to refer to the instance variable
this.title = title;
}
}
In this example, this.title refers to the instance variable title, while title refers to
the parameter.
Lecturer: Mercy Wairimu Gachoka
The this keyword public class MyClass {
private int value;
Invoking Current Object's Method: // Setter method
• this can be used to invoke methods of public void setValue(int value) {
the current object. This is particularly
useful when there's a local variable or // Using this to refer to the instance
parameter with the same name as an variable
instance variable: this.value = value;
}
}
Here, this.value ensures that we are
setting the value of the instance
variable, not the parameter.
Lecturer: Mercy Wairimu Gachoka
The this keyword
// MainApp.java
public class MainApp {
Invoking Current Object's Method: public static void main(String[] args) {
// Creating a Customer object
• Imagine a Customer class with a method to place an Customer customer = new Customer();
order. Using this helps clarify that the order is associated
with the current customer:
// Customer.java // Placing an order using the method
customer.placeOrder(12345);
public class Customer {
}
private String name;
}
private int orderId;
In this example, this.name and this.orderId ensure we are
// Method to place an order referring to the instance variables.
public void placeOrder(int orderId) {
// Using this to refer to the instance variable
this.orderId = orderId;
System.out.println("Order placed for customer " +
this.name + " with order ID: " + this.orderId);
}
}
Lecturer: Mercy Wairimu Gachoka
The this keyword public class MyClass {
private int value;
Invoking Current Object's Constructor:
• this can also be used to invoke the current object's // Parameterized constructor
constructor from another constructor in the same class. This
is known as constructor chaining: public MyClass(int value) {
this.value = value;
}
// Default constructor chaining the parameterized constructor
public MyClass() {
this(0); // Calling the parameterized constructor
}
}
Here, the default constructor this(0) calls the parameterized
constructor with a default value of 0.
Lecturer: Mercy Wairimu Gachoka
The this keyword
Consider a Rectangle class with a parameterized constructor for setting dimensions. The // MainApp.java
default constructor can use constructor chaining with this:
public class MainApp {
// Rectangle.java
public static void main(String[] args) {
public class Rectangle { // Creating a Rectangle object using the default constructor
private int length; Rectangle defaultRectangle = new Rectangle();
private int width;
// Creating a Rectangle object using the parameterized constructor
// Parameterized constructor Rectangle customRectangle = new Rectangle(10, 5);
}
public Rectangle(int length, int width) {
}
this.length = length;
this.width = width;
Output:
System.out.println("Parameterized constructor called. Length: " • Parameterized constructor called. Length: 0, Width: 0
+ length + ", Width: " + width);
• Default constructor called.
}
• Parameterized constructor called. Length: 10, Width: 5
This output shows that the default constructor is indeed chaining the parameterized
// Default constructor chaining the parameterized constructor constructor with default values when creating a defaultRectangle object, and the
parameterized constructor is directly called when creating a customRectangle object.
public Rectangle() {
this(0, 0); // Calling the parameterized constructor with default
values
System.out.println("Default constructor called.");
}
}
Lecturer: Mercy Wairimu Gachoka
Class Exercise: The this keyword
Create a class named Student with the following attributes:
• id (int)
• name (String)
• grade (char)
Implement a parameterized constructor in the Student class to initialize the attributes.
Implement getters and setters for all attributes in the Student class.
Create an application class (StudentApp) with the main method to demonstrate the usage of the
Student class:
• Create an instance of the Student class using the constructor.
• Use setters to update the values of the student attributes.
• Use getters to retrieve and display the student information.
Use the this keyword in the Student class constructor, getters, and setters to avoid naming
conflicts.
Lecturer: Mercy Wairimu Gachoka
Here's a skeletal structure to get you started:
// Student.java // Student.java
public class Student { public class Student {
private int id; private int id;
private String name; private String name;
private char grade; private char grade;
// Parameterized constructor using 'this' // Parameterized constructor using 'this'
public Student(int id, String name, char grade) { public Student(int id, String name, char grade) {
// TODO: Implement the constructor using 'this' to initialize attributes // TODO: Implement the constructor using 'this' to initialize attributes
} }
// Getter and setter methods using 'this' // Getter and setter methods using 'this'
// TODO: Implement getters and setters // TODO: Implement getters and setters
// Display student information // Display student information
public void displayInfo() { public void displayInfo() {
System.out.println("Student ID: " + id); System.out.println("Student ID: " + id);
System.out.println("Student Name: " + name); System.out.println("Student Name: " + name);
System.out.println("Student Grade: " + grade); System.out.println("Student Grade: " + grade);
} }
} }
Lecturer: Mercy Wairimu Gachoka
// Application.java
Bonus Example of Constructor public class Application {
// Person.java public static void main(String[] args) {
public class Person { // Creating a Person object using the constructor
private String name; Person person1 = new Person("John", 30);
private int age;
// Parameterized Constructor // details using the displayDetails method
public Person(String name, int age) { person1.displayDetails();
this.name = name;
this.age = age; // Using the sayHello method
person1.sayHello();
}
In this Application
// Method to display person details In this example: class:
public void displayDetails() { // Getting the name using the getName method
getName and String person1Name = person1.getName();
getName and
System.out.println("Name: " + name + ", Age: " + age);
} setName are getter System.out.println("Person 1's name: " + person1Name); getAge are used to
// Method to wish the person and setter access the values of
public void sayHello() { methods for the // Setting a new age using the setAge method the name and age
System.out.println("Hello, " + name + "!"); person1.setAge(35); fields, respectively.
name field.
} setName and
// Getter for the name getAge and setAge // Displaying updated details
setAge are used to
person1.displayDetails();
public String getName() { are getter and modify the values
}
return name;
setter methods for }
of the name and
}
the age field. Output:
age fields,
// Setter for the age
Name: John, Age: 30 respectively.of the
public void setAge(int age) {
this.age = age;
Hello, John! name and age
}
Person 1's name: John fields, respectively.
Lecturer: Mercy Wairimu Gachoka
Name: John, Age: 35
}
Setters and Getters
• In Java, getters and setters are methods used to access and modify
the values of private fields (instance variables) in a class. They are
part of the encapsulation concept, allowing controlled access to the
internal state of an object.
Lecturer: Mercy Wairimu Gachoka
Exercise on Constructors
1.Create a class named Book with the following attributes:
•title (String)
•author (String)
•publicationYear (int)
•price (double)
2.Implement a parameterized constructor in the Book class to initialize the attributes.
3.Implement getters and setters for all attributes in the Book class.
4.Create an application class (BookApp) with the main method to demonstrate the usage of the Book class:
•Create an instance of the Book class using the parameterized constructor.
•Use setters to update the values of the book attributes.
•Use getters to retrieve and display the book information.
•Ensure that the Book class is encapsulated, and access to attributes is controlled through getters and setters.
Lecturer: Mercy Wairimu Gachoka
Skeletal structure to get you started
// Book.java
// BookApp.java
public class Book {
public class BookApp {
private String title;
public static void main(String[] args) {
private String author;
// Create a Book instance using the constructor
private int publicationYear;
// TODO: Instantiate a Book object with sample values using the constructor
private double price;
// Update book information using setters
// Parameterized constructor
// TODO: Use setters to update values
// TODO: Implement the constructor
// Display book information using getters
// Getter and setter methods for title
// TODO: Use getters to display the book information
// TODO: Implement getters and setters for other attributes
}
}
// Display book information
public void displayBookInfo() {
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.println("Publication Year: " + publicationYear);
System.out.println("Price: $" + price);
}
}
Lecturer: Mercy Wairimu Gachoka
Instruction for students
1. Complete the Book class by implementing the parameterized
constructor, getters, and setters.
2. In the BookApp class, create a Book object using the constructor
and then update its information using setters.
3. Display the book information using getters and the displayBookInfo
method.
4. This exercise provides practice in creating a class with a constructor
and managing access to attributes through getters and setters.
Lecturer: Mercy Wairimu Gachoka
.
The final keyword
In Java, the final keyword can be applied to variables, methods, and classes, and its meaning varies depending on where it is used. The final keyword in
Java is used to create constants, prevent method overriding, prevent class extension, and create immutable method parameters
1. Final Variables:
When final is applied to a variable, it means that the variable's value cannot be changed once it has been assigned a value. This is essentially declaring a
constant.
Example:
public class Example {
final int myConstant = 10;
public static void main(String[] args) {
Example obj = new Example();
// Cannot reassign a value to a final variable
// obj.myConstant = 20; // Error: Cannot assign a value to final variable
System.out.println(obj.myConstant); // Output: 10
}
}
Lecturer: Mercy Wairimu Gachoka
Final Methods:
When final is applied to a method, it means that the method cannot be overridden by subclasses. This is commonly used to prevent further modification
of a method in a subclass.
• Example:
public class Parent {
// Final method
final void finalMethod() {
System.out.println("This method cannot be overridden.");
}
}
public class Child extends Parent {
// Attempting to override a final method results in a compilation error
// @Override
// void finalMethod() { } // Error: Cannot override the final method from Parent
}
Lecturer: Mercy Wairimu Gachoka
Final Classes:
• When final is applied to a class, it means that the class cannot be extended
(no subclasses can be created). This is often done for security reasons or to
prevent further modification of a class.
• Example:
final public class FinalClass {
// Class members and methods
}
// Attempting to extend a final class results in a compilation error
// class Subclass extends FinalClass { } // Error: Cannot extend final class
Lecturer: Mercy Wairimu Gachoka
Final Arguments:
When final is applied to method parameters, it means that the parameter cannot be modified inside the method.
Example:
public class Example {
void modifyValue(final int x) {
// Cannot reassign a value to a final parameter
// x = x + 1; // Error: Cannot assign a value to final variable
System.out.println(x);
}
public static void main(String[] args) {
Example obj = new Example();
obj.modifyValue(5); // Output: 5
}
}
Lecturer: Mercy Wairimu Gachoka