Saturday 3 August 2013

18:different types of method declaration

Learning Objectives
After completing this session, you will be able to:
‰  Identify constructors and the different types of method declaration
Constructors
‰  Java provides a special construct named constructor exclusively for creating an object
of a class and initializing its instance variables.
‰  Constructors should have the same name as the name of the class.
‰  It is generally declared as public.
‰  It may have optional list of arguments.
‰  It does not have any return type and not even void.
‰  You cannot invoke a constructor on an existing object.
‰  You can use a constructor only in combination with the new operator.
To declare a constructor, you write,
<modifier> <className> (<parameter>*) {
<statement>*
}
Default Constructor (Method)
The default constructor (no-arg constructor):
‰  Constructor without any parameters
‰  If the class does not specify any constructors, then an implicit default constructor is
created
Example:Default Constructor Method of StudentRecord Class
public StudentRecord()
{
//some code here
}
Overloading Constructor Methods
public StudentRecord()
//some initialization code here
}
public StudentRecord(String temp) {
this.name = temp;
}
public StudentRecord(String name, String address {
this.name = name;
this.address = address;
}
public StudentRecord(double mGrade, double eGrade,
double sGrade) {
mathGrade = mGrade;
englishGrade = eGrade;
scienceGrade = sGrade;
}
Applying Constructors
To apply these constructors, you have the following code:
public static void main( String[] args ){
//create three objects for Student record
StudentRecord annaRecord=new StudentRecord("Anna");
StudentRecord beahRecord=new StudentRecord("Beah",
"Philippines");
StudentRecord crisRecord=new
StudentRecord(80,90,100);
//some code here
}
“this()” Constructor Call
‰  Constructor calls can be chained, which means that you can call another constructor
from inside another constructor.
‰  You use the this()method call for this.
‰  There are a few things to remember when using the this()method constructor call:
‰  When using thisconstructor call, it must occur as the first statement in a constructor.
‰  It can only be used in a constructor definition. The thiscall can then be followed by
any other relevant statements.
Example of “this()” Constructor Call
1: public StudentRecord(){
2: this("some string");
3:
4: }
5:
6: public StudentRecord(String temp){
7: this.name = temp;
8: }
9:
10: public static void main( String[] args )
11: {
12:
13: StudentRecord annaRecord = new StudentRecord();
14: }
“this” Reference
The thisreference:
‰  Refers to current object instance itself
‰  Used to access the instance variables shadowed by the parameters
‰  To use the thisreference, you type, this.<nameOfTheInstanceVariable>
‰  You can only use the thisreference for instance variables and not for static or class
variables
The this reference is assumed when you call a method from the same object.
public class MyClass {
void aMethod() {
// same thing as this.anotherMethod()
anotherMethod();
}
void anotherMethod() {
// method definition here...
}
}
Example of “this” Reference
public void setAge( int age ){
this.age = age;
}
Declaring Methods
To declare methods you write,
<modifier> <returnType>
<name>(<parameter>*) {
<statement>*
}
Where:
‰  <modifier> can carry a number of different modifiers
‰  <returnType> can be any data type (including void)
‰  <name> can be any valid identifier
‰  <parameter> can be one or more parameters passed as argument to the method.
Each <parameter> is associated with a parameter type (primitive or object) and a
parameter name.
Accessor (Getter) Methods
Accessor methods:
‰  Used to read values from your class variables (instance or static)
‰  Usually written as get<NameOfInstanceVariable>
‰  It also returns a value
Example 1: Accessor (Getter) Method
Example:
public class StudentRecord {
private String name;
:
public String getName(){
return name;
}
}
where:
‰  public means that the method can be called from objects outside the class.
‰  String is the return type of the method. This means that the method should return a
value of type String.
‰  getName is the name of the method.
‰  () means that your method does not have any parameters.
Example 2: Accessor (Getter) Method
public class StudentRecord {
private String name;
// some code
// An example in which the business logic is
// used to return a value on an accessor method
public double getAverage(){
double result = 0;
result=(mathGrade+englishGrade+scienceGrade)/3;
return result;
}
}
Mutator (Setter) Methods
Mutator Methods:
‰  Used to write or change values of yourclass variables (instance orstatic)
‰  Usually written as set<NameOfInstanceVariable>
Example:Mutator (Setter) Method
Example:
public class StudentRecord {
private String name;
:
public void setName( String temp ){
name = temp;
}
}
Where:
‰  public means that the method can be called from objects outside the class.
‰  void means that the method does not return any value.
‰  setName is the name of the method.
‰  (String temp) is a parameter thatwill be used inside your method.
Multiple Return Statements
‰  You can have multiple return statements for a method as long as they are not on the
same block.
‰  You can also use constants to return values instead of variables.
Example: Multiple Return Statements
public String getNumberInWords( int num ){
String defaultNum = "zero";
if( num == 1 ){
return "one"; //return a constant
}
else if( num == 2){
return "two"; //return a constant
}
//return a variable
return defaultNum;
}
Static Methods
Example:
public class StudentRecord {
private static int studentCount;
public static int getStudentCount(){
return studentCount;
}
}
where,
‰  public means that the method can be called from objects outside the class.
‰  static means that the method is static and should be called by typing,
[ClassName].[methodName. For example,in this case, you call the method
StudentRecord.getStudentCount()
‰  int is the return type of the method. This means that the method should return a value
of type int.
‰  getStudentCount is the name of the method.
‰  () means that your method does not have any parameters.
Coding Guidelines
‰  Method names should start with a small letter
‰  Method names should be verbs
‰  Always provide documentation before the declaration of the method
When to Define Static Method?
When the logic and state does not involve specific object instance:
‰  Computation method: add(int x, int y) method
When the logic is a convenience without creating an object instance:
‰  Integer.parseInt();
Source Code for StudentRecord Class
public class StudentRecord {
// Instance variables
private String name;
private String address;
private int age;
private double mathGrade;
private double englishGrade;
private double scienceGrade;
private double average;
private static int studentCount;
/**
* Returns the name of the student (Accessor method)
*/
public String getName(){
return name;
}
/**
* Changes the name of the student (Mutator method)
*/
public void setName( String temp ){
name = temp;
}
/**
* Computes the average of the english, math and science
* grades (Accessor method)
*/
public double getAverage(){
double result = 0;
result = ( mathGrade+englishGrade+scienceGrade )/3;
return result;
}
/**
* returns the number of instances of StudentRecords
* (Accessor method)
*/
public static int getStudentCount(){
return studentCount;
}
Sample Source Code that uses StudentRecord Class
public class StudentRecordExample
{
public static void main( String[] args ){
//create three objects for Student record
StudentRecord annaRecord = new StudentRecord();
StudentRecord beahRecord = new StudentRecord();
StudentRecord crisRecord = new StudentRecord();
//set the name of the students
annaRecord.setName("Anna");
beahRecord.setName("Beah");
crisRecord.setName("Cris");
//print anna's name
System.out.println( annaRecord.getName() );
//print number of students
System.out.println("Count="+StudentRecord.getStudentCount());
}
}
Program Output
Anna
Student Count = 0
Try It Out
Problem Statement:
Write a program that illustrate the use of ‘this’ statement in constructor overloading.
Code:
public class Box {
double x, y, width, height;
public Box(double x, double y, double width, double height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public Box(double x, double y) {
this(x, y, 10, 10);
}
Tips and Tricks:
‰  How can you differentiate a constructor from a method?
‰  Can you also have a method that has the same name as the class?
‰  Are constructors inherited? If you do not provide a constructor but your superclass
does,then do you get the superclass constructor instead of the default?
‰  A static method cannot access a variable that is not static.
‰  But can a method that is not static access a static variable?
Solution:
‰  Java lets you to declare a method with the same name as your class, which does not
make it a constructor, though.
‰  The thing that separates a method from a constructor is the return type.
‰  Methods must have a return type, but constructors cannot have a return type and not
even void.
‰  No, constructors are not inherited.
‰  A method that is not static in a class can always call a static method in the class or
access a static variable of the class.
Summary
‰  A constructor is always invoked when a new object is created.
‰  Every class, even an abstract class, has at least one constructor.
‰  Interfaces do not have constructors.
‰  Constructors must have the same name as the class.
‰  Constructors can use any access modifier (even private!)
‰  The default constructor is a no-arg constructor with a no-arg call to super().
‰  The first statement of every constructor must be a call to either this() (an overloaded
constructor) or super().
‰  Calls to this() and super() cannot be in the same constructor, you can have one or the
other, but never both.

No comments:

Post a Comment