Java Programming : Returning an
Object from a Method
Dr. Ei Ei Moe
Lecturer
©[Link]
Objectives
• To understand how to return objects from methods
• To know how to use the reserved keyword ‘this’ indicates the current object
Faculty of Computer Science
Returning Objects from Methods
• A method can return an object in a similar manner as that of returning a variable of
primitive types from methods.
• When a method returns an object, the return type of the method is the name of the
class to which the object belongs.
<modifier> <return type> <method name> ( <parameters> ) {
<statements>
}
class Sample {
public Sample twiceSample() { }
}
Faculty of Computer Science
Returning Objects Sample
Return type indicates the class of an object
public Fraction simplify( ) {
Fraction simp;
int num = getNumerator();
int denom = getDenominator();
int gcd = gcd(num, denom);
simp = new Fraction(num/gcd, denom/gcd);
Return an instance of
return simp; the Fraction class
}
Faculty of Computer Science
A Sample Call to simplify
f1 = new Fraction (24, 26); public Fraction simplify( ) {
f2 = [Link]();
int num = getNumerator();
f1 int denom = getDenominator();
simp
f2 int gcd = gcd(num, denom);
Fraction simp = new
: Fraction : Fraction
Fraction(num/gcd, denom/gcd);
numerator numerator
24 2
return simp;
denominator denominator }
26 3
Faculty of Computer Science
Example: Returning Objects
public class Sample {
int num; Data field
Sample(int n) { Argument Constructor Output
num = n; }
public Sample twiceSample() { Method
5
Sample s = new Sample(num * 2); 10
return s; }
public static void main(String[] args) {
Sample sobj = new Sample(5);
[Link]([Link]);
Sample sobj1 = [Link]();
[Link]([Link]);
}
} Faculty of Computer Science
Reserved Word this
• The reserved word this is called a self-referencing pointer because it refers to an
object from the object's method.
: Object
this
Faculty of Computer Science
The use of this in the add Method
public Fraction add (Fraction frac) {
int a, b, c, d;
Fraction sum;
a = [Link](); Get the receiving object’s num
b = [Link](); Get the receiving object’s denom
c = [Link](); Get frac’s num
d = [Link](); Get frac’s denom
sum = new Fraction(a*d + b*c, b*d);
return sum;
} Faculty of Computer Science
The use of this in the add Method
f3 = [Link](f2)
f1 this
this points to f1
f2 frac
f3
: Fraction : Fraction
numerator numerator
24 2
denominator denominator
26 3
Faculty of Computer Science
The use of this in the add Method
f3 = [Link](f1)
f1 this
f2 frac this points to f2
f3
: Fraction : Fraction
numerator numerator
24 2
denominator denominator
26 3
Faculty of Computer Science
Using this Refer to Data Members
class Person {
int age;
public void setAge(int val) {
This refers to the [Link] = val; This refers to the
parameter
data member
}
...
}
Faculty of Computer Science
Summary
• How to return objects from methods
• How to use this keyword
NEXT Topic
• Overloaded Methods and Constructors
Faculty of Computer Science