Ch08Functions(Methods)
Ch08Functions(Methods)
08: FUNCTIONS/METHODS
8.1 Function
• A function is a block of organized and reusable code that is used to perform a specific
task.
• Functions provide better modularity for your application and a high degree of code
reusing.
Invoking : To invoke this type of function, calling statement can be written in following 3 ways:
1. As the condition for a control statement (if , while etc.).
e.g. if (<function-name>(arguments) )
2. As an assignment to a variable.
e.g. Variable = <function-name>(arguments);
3. In printing statement
e.g. System.out.println (<function-name>(arguments) );
e.g.
class sample
{
int n;
public sample ( int nn)
{
n = nn;
}
public int factorial ( )
{
int f=1;
for ( int i =1; i<=n;i++)
{
f = f*i;
}
return f;
}
public static void main( int num)
{
sample ob = new sample(num);
int fact=ob.factorial(); // calling as an assignment
System.out.println(“Factorial =“+fact);
System.out.println(“Factorial =“+ob.factorial()); // In printing statement
if(ob.factorial() == 120) // Calling as a condition
System.out.print(“number is 5”);
}
}//end of class
8.13 The “this” Keyword
The “this” reference stores the address of current–calling object.
The keyword “this”
1. only pertains to an instance method, not to a class/static method.
2. is accessible inside instance method.
3. distinguish between instance variable and local variable ( if these have same name and
used in same block).
class Abc
{
int n; // instance variable
public Abc (int n)
{
this.n = n; // “this.n” represents instance variable.
}
}
8.14: Constructors A constructor initializes an object, with some legal values, immediately
upon creation.
Properties of a constructor:
1. It has same name as of the class name.
2. It doesn’t have any return type not even void.
3. It invoked automatically as soon as the object is created.
Types of Constructors
• Default constructor: Constructor that doesn’t have parameter list.
• Parameterized constructor: Constructor that has parameter list.
• Copy constructor: Constructor that has an object as the parameter. It is used to initialize
an object with values of an existing object of the same class.
e.g.
public class Sample
{
int a; // instance(object) variable
public Sample() // default constructor
{
a=0;
}
public sample( int x) // Parameterized constructor
{
a=x;
}
public sample(Sample ob) // Copy constructor
{
a=ob.a;
}
public void input() // Member function
{
a=10;
}
public static void main ()
{
Sample ob1 = new Sample(); // To invoke default constructor
Sample ob2 = new Sample(8); // To invoke Parameterized constructor
Sample ob3 = new Sample(ob2); //To invoke Copy constructor
ob1.input(); // To invoke input( ) function
}
}