We can return an object from a method. The data type for such method is a class type. Java Program[ObjRetDemo.java]
Returning Objects
• We can
return an object from a method. The data type for such method is a class type.
Java
Program[ObjRetDemo.java]
public
class ObjRetDemo {
int a;
ObjRetDemo(int
val)
{
a=val;
}
ObjRetDemo
fun()
{
ObjRetDemo
temp = new ObjRetDemo (a+5); //created a new object return temp; //returning
the object from this method
}
}
class
ObjRet {
public
static void main(String args[])
{
ObjRetDemo
obj2=new ObjRetDemo (20);
ObjRetDemo
obj1;
obj1=obj2.fun();//obj1
gets the value from object temp System.out.println("The returned value is
= "+obj1.a);
}
}
Output
F:\test>javac
ObjRetDemo.java
F:\test>java
ObjRet
The
returned value is = 25
Ex. 2.3.1: Write Java program for
computing Fibonacci series.
Sol.:
/******************************************************************
Program
for computing the number in the fibonacci series at certain location. For
example the eighth number in fibonacci series will be 21. The fibonacci series
is 1 1 2 3 5 8 13 21 34...
*****************************************************************/
import
java.io.*;
import
java.util.*;
class
Fibonacci
{
public
int fib(int n)
{
int x,y;
}
if(n<=1)
return
n;
x=fib(n-1);
y=fib(n-2);
return
(x+y);
}
}//end
of class
class
FibonacciDemo
{
public
static void main(String[] args) throws IOException
{
Fibonacci
f= new Fibonacci();
int n=8;
System.out.println("\nThe
number at "+n+" is "+f.fib(n));
}
}
Output
D:\>javac
FibonacciDemo.java
D:\>java
FibonacciDemo
The
number at 8 is 21
Object Oriented Programming: Unit II: Inheritance, Packages and Interfaces : Tag: : with Example Java Programs - Returning Objects
Object Oriented Programming
CS3391 3rd Semester CSE Dept | 2021 Regulation | 3rd Semester CSE Dept 2021 Regulation