Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 22

Domasi College of Education

Unit 4

Methods and Constructors


Introduction
In the previous unit, you saw how inheritance,
polymorphism, encapsulation and interfaces are
implemented in Java. In this unit, you will learn
methods and constructors and how they are
implemented in Java.

Success Criteria
By the end of this Unit, you should be able to:
 define a method
 describe the components of a method
 state types of methods in Java
 implement methods using Java
 explain methods overloading and overriding
 describe the Java constructor
 state types of Java constructors
 state the difference between Java methods and
constructors
Key Words
You will find the following key words or phrases in this
unit: method, constructor, method overloading,
access modifiers and method overriding. Watch for
these and make sure that you understand what they
mean and how they are used in the unit.

Computer Programming II, Object-Oriented 4-1


Domasi College of Education

Java Methods
In Unit 2, you were introduced to methods. In Java, a
method is defined as a block of code or collection of
statements or a set of code grouped together to
perform a certain task or operation (JavaTPoint, n. d).
A method can be invoked at any point in the program.
This is done by utilizing the name of the method.

You should note that all method names should start


with a Lower Case letter.

For example: static void myMethod() {


// the method’s code goes here
}

When two or more words are used to form the name of


the method, then each inner word's first letter should
be in Upper Case.

Example: static void myMethodName()

From the above examples, you will notice that after the
method’s name, there is a pair of parentheses, (),
followed by braces {}.

Methods are also called functions.

Components of a Method

Method declarations have the following components, in


order:
1. Modifiers—such as public, private and protected
2. The return type—the data type of the value
returned by the method or void if the method
does not return a value.
3. The method name – must start with a lower case.
4. The parameter list in parenthesis—a comma-
delimited list of input parameters, preceded by
their data types, enclosed by parentheses, (). If
there are no parameters, you must use empty
parentheses.

Computer Programming II, Object-Oriented 4-2


Domasi College of Education

5. The method body, enclosed between braces—the


method's code, including the declaration of local
variables, goes here.

Let us use the following Java code to understand these


components better:

public int myThirdYear(int a, int b){

// method body

From the above code, you should note that public is a


modifier, int is a return type, myThirdYear is the
method name and (int a, int b) is the parameter list.

Note also that public int myThirdYear(int a, int b) is


Method Header and myThirdYear(int a, int b) is the
Method Signature (the method's name and the
parameter types).

Java Access Modifiers

Access modifier specifies the visibility of the method.


Java provides four types of access modifiers and these
are:

public: The method is accessible by all classes

private: The method is accessible only in the classes in


which it is defined.
protected: The method is accessible within the same
package or subclasses in a different package.

default: When no any access modifier is used, Java


uses default access modifier by default. It is visible to
the package.

Types of Methods in Java

There are two methods in Java and these are:


1. Predefined Method
2. User-defined Method
Predefined Method

Computer Programming II, Object-Oriented 4-3


Domasi College of Education

You can define predefined methods as built-in methods


in Java that are readily available for use. These
methods are also called standard library methods.
These methods can directly be used by calling them in
the program at any point.
Examples of predefined methods include length(),
equals(), compareTo(), sqrt(), etc.
Each and every standard library method is defined
inside a class. For example, print() method is defined
in the java.io.PrintStream class and sqrt() is
defined in Math class.
Consider the following Java program:
public class CollegeCampus
{
public static void main(String[] args)
{
System.out.print("The maximum number
is: " + Math.max(100,78));
}
}
In the above example, you should note that there are
three predefined methods that have been used which
are main(), print(), and max(). The max() method is
a method of the Math class that returns the greater of
two numbers.
User-defined Method
This is the method written by the user or programmer.
You should note that these methods are modified
according to the requirement. Here is an example of
user-defined method:

//user defined method


public static void findEvenOdd(int num)
{
//method body
if(num%2==0)

Computer Programming II, Object-Oriented 4-4


Domasi College of Education

System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
From the above example, you should note that a
method called findEvenOdd()is defined. This method
has a parameter num of type int.
The method body contains the steps to check whether
the number is even or odd. If the number is even, it
prints the number is even, else prints the number is
odd.
Static methods
Notice that you can use static or non-static methods in
both types of Java methods.
A static method has static keyword. It is a method
that belongs to a class rather than an instance of a
class.
The following is an example of static method:

public static void findEvenOdd(int num) {

}
Characteristics of static methods
Aravindan (n. d), explains that a static method can
access static methods and variables as follows:
1. A static method can call only other static
methods; it cannot call a non-static method
2. A static method can be called directly from the
class, without having to create an instance of
the class
3. A static method can only access static
variables; it cannot access instance variables
4. Since the static method refers to the class, the
syntax to call or refer to a static method is:
class name.method name
5. To access a non-static method from a static
method, create an instance of the class

Computer Programming II, Object-Oriented 4-5


Domasi College of Education

Instance Methods
These are methods that require an object of its class to
be created before calling it. They are also called non-
static methods.
Below is an example of instance method:
public void example(String random) {
}
You must take note that the void keyword allows us to
create methods which do not return a value.
Characteristics of Non-Static Methods
Aravindan (n. d), explains that a non-static method in
Java can access static methods and variables as
follows:
1. A non-static method can access any static
method without creating an instance of the class
2. A non-static method can access any static
variable without creating an instance of the class
because the static variable belongs to the class

Types of instance methods


There are two types of instance method:
 Accessor Method
 Mutator Method

Accessor method reads the instance variable(s). You


can easily identify it because the method is prefixed
with the word get. As such, accessor method is also
known as getters. It returns the value of the private
field. It is used to get the value of the private field.
Here is an example:
public int getId()
{
return Id;
}
Mutator method reads the instance variable(s) and also
modify the values. You can easily identify it because

Computer Programming II, Object-Oriented 4-6


Domasi College of Education

the method is prefixed with the word set. Mutator


method is also known as setters or modifiers. It does
not return anything. It accepts a parameter of the
same data type that depends on the field. It is used to
set the value of the private field.
Here is an example:
public void setRoll(int roll)
{
this.roll = roll;
}
Java main method
You may wish to know that main method is the entry
point of any Java program. Its syntax is always public
static void main(String[] args).
You can only change the name of String array
argument, for example you can change args to
myStringArgs.
Calling Java Methods
To call a static method in Java, you should write the
method's name followed by two parentheses () and a
semicolon;
Example (Copy this code and run it in your IDE):
public class Nalikule {
static void myMethod() {
System.out.println("Welcome to Computer
Programming class!");
}

public static void main(String[] args) {


//calling static method
myMethod();

}
}

Computer Programming II, Object-Oriented 4-7


Domasi College of Education

On the other hand, a non-static method is always


accessed using the object of class.
See an example below (Copy this code and run it in
your IDE):

class NalikuleCampus
{
public void display()
{
System.out.println("I am non-static
method");
}
public static void main(String agrs[])
{
NalikuleCampus obj=new
NalikuleCampus();
obj.display();
}
If you try to access it directly like this: display() then
you will get compilation error.
Method Overloading
You should take note that method overloading occurs
when a class has two or more methods by the same
name but different parameters (Hejazi, 2019).
Example (Copy this code and run it in your IDE):
public class Sum {
static int sum(int x, int y) {
return x + y;
}

static double sum(double x, double y) {


return x + y;
}

Computer Programming II, Object-Oriented 4-8


Domasi College of Education

public static void main(String[] args) {


int int_sum = sum(10, 20);
double double_sum = sum(10.5, 23.67);

System.out.println("int: " + int_sum);


System.out.println("double: " + double_sum);
}
}
Benefits of using Method Overloading
Great Learning (2021) identifies the following benefits:
 Method overloading increases the readability of
the program.
 This provides flexibility to programmers so that
they can call the same method for different types
of data.
 This makes the code look clean.
 This reduces the execution time because the
binding is done in compilation time itself.
 Method overloading minimises the complexity of
the code.
 With this, we can use the code again, which saves
memory.

Disadvantages of Method Overloading

 Difficult for the beginner to understand.


 It requires more significant effort spent on
designing the architecture (i.e., the arguments'
type and number).

There are two possible ways to overload and these are:

1. Changing Number of arguments.

Example (Copy this code and run it in your IDE):

class Plants
{

Computer Programming II, Object-Oriented 4-9


Domasi College of Education

void multiply(int a, int b)


{
System.out.printIn("Result is"+
(a*b)) ;
}
void multiply(int a, int b, int c)
{
System.out.printIn("Result is"+
(a*b*c));
}
public static void main(String[] args)
{
Plants obj = new Plants();
obj.multiply(8,5);
obj.multiply(4,6,2);
}
}

2. Changing the data types.

Example (Copy this code and run it in your IDE):

class Car
{
static int add(int a, int b)
{
return a+b;
}
static double add(double a, double b)
{
return a+b;
}
}
class Car2
{
public static void main(String[] args)
{
System.out.println(Sum.add(17,13));
System.out.println(Sum.add(10.4,10.6));
}
}

Method overriding

Computer Programming II, Object-Oriented 4-10


Domasi College of Education

Now that you know what method overloading is all


about, you should turn to method overriding. Method
overriding in Java occurs when a subclass (child class)
has the same method as declared in the parent class.

Example (Copy this code and run it in your IDE):

class People{
//Overridden method
public void eat()
{
System.out.println("People are
eating");
}
}
class Girl extends People{
//Overriding method
public void eat(){
super.eat();
System.out.println("Girl is eating");

}
public static void main( String args[]) {
Girl obj = new Girl();
//This will call the child class
version of eat()
obj.eat();
}
}

You should note that we have a child class Girl and a


parent class People. The Girl class extends People
class. Both the classes have a common method void

Computer Programming II, Object-Oriented 4-11


Domasi College of Education

eat(). Girl class is giving its own implementation to


the eat() method or in other words it is overriding the
eat() method. In other words, Girl class prints Girl is
eating instead of People are eating.
To call the overridden method, we use the super
keyword.
For example (Copy this code and run it in your IDE):

class OOP{
public void myMethod()
{
System.out.println("Overridden method");
}
}
class Domcol extends OOP{
public void myMethod(){
//This will call the myMethod() of
parent class
super.myMethod();
System.out.println("Overriding method");
}
public static void main( String args[]) {
Domcol obj = new Domcol();
obj.myMethod();
}
}

Advantage of method overriding

Computer Programming II, Object-Oriented 4-12


Domasi College of Education

 The class can give its own specific


implementation to an inherited method without
even modifying the parent class code.

Disadvantages of method overriding


The following are some of the disadvantages of method
overriding:
 Cannot override static methods.
 Cannot override constructors.
 If a method cannot be inherited, it cannot be
overridden.

Rules for Method Overriding


The following rules outlined by TutorialsPoint (n. d),
may be helpful for you:
 The argument list should be exactly the same as
that of the overridden method.
 The return type should be the same or a subtype
of the return type declared in the original
overridden method in the superclass.
 The access level cannot be more restrictive than
the overridden method's access level. For
example: If the superclass method is declared
public then the overriding method in the sub
class cannot be either private or protected.
 Instance methods can be overridden only if they
are inherited by the subclass.
 A method declared final cannot be overridden.
 A method declared static cannot be overridden
but can be re-declared.
 If a method cannot be inherited, then it cannot
be overridden.
 A subclass within the same package as the
instance's superclass can override any
superclass method that is not declared private or
final.

Computer Programming II, Object-Oriented 4-13


Domasi College of Education

 A subclass in a different package can only


override the non-final methods declared public
or protected.
 An overriding method can throw any uncheck
exceptions, regardless of whether the overridden
method throws exceptions or not. However, the
overriding method should not throw checked
exceptions that are new or broader than the ones
declared by the overridden method. The
overriding method can throw narrower or fewer
exceptions than the overridden method.
 Constructors cannot be overridden.

Self Evaluation Activity 4-a


1. State two types of methods in Java.
2. What type of method is shown in the following code
below?
public int getId()
{
return Id;
}
3. Explain the difference between method overloading and
method overriding.

Answers to this activity are at the end of the unit.

Practise Activity
A nonnegative integer is called a palindrome if it reads
forward and backward in the same way. For example, the
numbers 5, 121, 3443, and 123454321 are palindromes.
Write a method that takes as input a nonnegative integer
and returns true if the number is a palindrome; otherwise,
it returns false. Also write a program to test your method.

Computer Programming II, Object-Oriented 4-14


Domasi College of Education

Java Constructors
A constructor in Java is considered as a special
method that is used to initialize objects. You should
note that every time an object is created using the
new() keyword, at least one constructor is called.
Constructor name must match the class name, and it
cannot have a return type (like void).
Look at the example below:
// Create a Main class
public class Domcol {
int x; // Create a class attribute

// Create a class constructor for the Main


class
public Domcol() {
x = 5; // Set the initial value for the
class attribute x
}

public static void main(String[] args) {


Domcol myObj = new Domcol(); // Create an
object of class Main (This will call the
constructor)
System.out.println(myObj.x); // Print the
value of x
}
}

Rules for creating Java constructor


Make sure you adhere to the following rules:
 Constructor name must be the same as its class
name
 A Constructor must have no explicit return type

Computer Programming II, Object-Oriented 4-15


Domasi College of Education

 A Java constructor cannot be abstract, static,


final, and synchronized

Types of Constructors

There are two types of constructors in Java and these


are:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Java Default Constructor


This type of constructor has no any parameter.
Example:
//Java Program to create and call a default
constructor
class MotorCycle{
//creating a default constructor
MotorCycle(){
System.out.println("It is running");
}
//main method
public static void main(String args[]){
//calling a default constructor
MotorCycle cycle=new MotorCycle();
}
}
You should note that the default constructor is used to
provide the default values to the object like 0, null,
etc., depending on the type.

Parameterized constructor
It is a constructor which has a specific number of
parameters.

The parameterized constructor is used to provide


different values to distinct objects. However, you can
provide the same values also.

Computer Programming II, Object-Oriented 4-16


Domasi College of Education

Example:

//Java Program to demonstrate the use of


the parameterized constructor.
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){
System.out.println(id+" "+name);
}

public static void main(String args[]){


//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of
object
s1.display();
s2.display();
}
}

Just like in methods, constructors can also be


overloaded.

Differences between constructor and method in


Java

JavaTPoint (n. d), outlines the following differences:

Java Constructor Java Method


A method is used to
A constructor is used to
expose the behavior of
initialize the state of an object.
an object.
A constructor must not have a A method must have a
return type. return type.
The constructor is invoked The method is invoked
implicitly. explicitly.
The Java compiler provides a The method is not
default constructor if you don't provided by the

Computer Programming II, Object-Oriented 4-17


Domasi College of Education

have any constructor in a class. compiler in any case.


The method name may
The constructor name must be
or may not be same as
same as the class name.
the class name.

Self-Evaluation Activity 4-b


1. What is constructor in Java?
2. What would be behaviour if the constructor has a return
type?
3. State two types of constructors.
4. What are the rules for defining constructor in a class?

Answers to this activity are at the end of the unit.

Practise Activity
Write a program to print the names of students by
creating a Student class. If no name is passed while
creating an object of Student class, then the name
should be "Unknown", otherwise the name should be
equal to the String value passed while creating object
of Student class.

Summary
In this unit, you have been introduced to methods and
constructors.

Computer Programming II, Object-Oriented 4-18


Domasi College of Education

 A method is defined as a block of code or collection of


statements or a set of code grouped together to
perform a certain task or operation
 Predefined and User-defined methods are types of
Java methods
 Method overloading occurs when a class has two or
more methods by the same name but different
parameters
 Method overriding in Java occurs when a subclass
(child class) has the same method as declared in the
parent class
 A constructor in Java is considered as a special
method that is used to initialize objects
 Types of Java constructors are Default constructor
(no-arg constructor) and Parameterized constructor

Reflection
Which part of this unit have you found so challenging?
Write a brief summary of what you have learned in this
unit and how it will impact your skills in programming.

Unit 4 Test
1. Why constructors in Java cannot be static?

2. Write a program with a method named


getTotal that accepts two integers as an
argument and return its sum. Call this
method from main( ) and print the results.
3. A prime number is a number that is evenly
divisible only by itself and 1. For example,
the number 5 is prime because it can be
evenly divided only by 1 and 5. The
number 6, however, is not prime because
it can be divided evenly by 1, 2, 4, and 6.
Write a method named isPrime, which
takes an integer as an argument and
returns true if the argument is a prime
number, or false otherwise. Also write
main method that displays prime numbers
between1 to 500.

Computer Programming II, Object-Oriented 4-19


Domasi College of Education

Answers to Unit 4 Activities


Answers to Activity 4-a
1. Predefined and User-defined methods
2. Accessor method
3. Method overloading occurs when a class has two or
more methods by the same name but different
parameters while method overriding in Java occurs
when a subclass (child class) has the same method as
declared in the parent class.

Answers to Activity 4-b


1. A constructor in Java is a special method that is
used to initialize objects
2. The output is compilation error. This is so
because the constructor cannot have a return
type. It should create and return new object.
Hence it would give compilation error.
3. Default constructor (no-arg constructor) and
Parameterized constructor (with a parameter).
4. Here are the rules:
a. Constructor name must be the same as its
class name
b. A Constructor must have no explicit
return type
c. A Java constructor cannot be abstract,
static, final, and synchronized

Computer Programming II, Object-Oriented 4-20


Domasi College of Education

Answers to Unit 4 Test


1. The constructors cannot be static in Java. When
we declare a method as static, it means the
method belongs to the class and not to a specific
object. But the constructor is always invoked to
the reference of objects. So, there is no sense in
making a constructor static.

2. Here is the solution:

import java.util.Scanner;

public class SumTwoNumber


{
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
int num1, num2;

System.out.print("Enter first number: ");


num1 = console.nextInt();

System.out.print("Enter second number:


");
num2 = console.nextInt();

int sum = getTotal(num1, num2);

System.out.println("Sum: " + sum);


}

public static int getTotal(int number1, int


number2)
{
return number1 + number2;
}

Computer Programming II, Object-Oriented 4-21


Domasi College of Education

3. Here is the solution:

public class PrimeNumbers


{
public static void main(String[] args)
{
for(int i = 1; i <= 500; i++)
{
if(isPrime(i))
{
System.out.print(i + " ");
}
}
}
public static boolean isPrime(int number)
{
for(int i = 2; i < number; i++)
{
if(number % i == 0)
{
return false;
}
}
return true;
}
}

Computer Programming II, Object-Oriented 4-22

You might also like