CHAPTER 4
DEFINING YOUR OWN CLASS – INTERMEDIATE
METHOD OVERLOADING
In same class, if name of the method remains common but the number and type of parameters
are different, then it is called method overloading in Java.
class overLoading
{ public static void main(String[] args)
{ functionOverload obj = new functionOverload();
[Link](1,2,3);
[Link](\"Life at \", \"?\");
[Link](11.5, 22.5);
}
}
class functionOverload
{
void add(int a, int b, int c) {
int sum = a + b + c;
[Link](\"Sum of a+b+c is \"+sum);
}
void add(double a, double b) {
double sum = a + b;
[Link](\"Sum of a+b is \"+sum);
}
void add(String s1, String s2)
{
String s = s1+s2;
[Link](s);
}
}
RESERVED WORD this
• The reserved word this is called a self-referencing pointer because it refers to an
object from the object's method.
• Example 1: (show the use of this to call a method of a receiving object)
public Fraction add(Fraction frac) {
int a,b,c,d;
Fraction sum;
a = [Link](); //get the receiving
b = [Link](); //object's num and denom
c = [Link](); //get frac's num
d = [Link](); //and denom
sum = new Fraction(a*d + b*c, b*d);
return sum;
}
Example 2: (It can be used to refer to a data member as well)
class Person {
int age;
public void setAge(int age) {
[Link] = age;
}
. . .
}
Example 3: (To call a constructor from another constructor of the same class, we use
the reserved word this)
public Fraction( ) { //creates 0/1
this(0.1);
}
public Fraction(int number) { //creates number/1
this(number, 1);
}
public Fraction(Fraction frac) { //copy constructor
this([Link]();
[Link]());
}
public Fraction(int num, int denom) {
setNumerator(num);
setDenominator(denom);
}
OBJECTS AS PARAMETER
Example 1:
class ObjectPrinter
{
public void print(String st)
{
[Link]("Value of parameter: " + st);
}
}
class OPTester
{
public static void main (String[] args)
{
String message = "Only One Object" ;
ObjectPrinter op = new ObjectPrinter();
[Link]("First value of message: " + message);
[Link](message);
[Link]("Second value of message: " + message);
}
}
Example 2:
class MyPoint
{
public int x=3, y=5 ;
public void print()
{
[Link]("x = " + x +
"; y = " + y );
}
}
class PointDoubler
{
public void twice( MyPoint parm )
{
[Link]("Enter PointDoubler");
[Link]() ;
parm.x = parm.x * 2 ;
parm.y = parm.y * 2 ;
[Link]() ;
[Link]("Leave PointDoubler");
}
}
class PointTester
{
public static void main ( String[] args )
{
MyPoint pt = new MyPoint();
PointDoubler dbl = new PointDoubler();
[Link]();
[Link]( pt );
[Link]();
}
}
Example 3:
public class Circle {
/** The radius of the circle */
private double radius;
private String cirName;
/** The number of the objects created */
static int numberOfObjects = 0;
/** Construct a circle with radius 1 */
public Circle() {
radius = 1.0;
cirName = "Unknown";
numberOfObjects++;
}
/** Construct a circle with a specified radius & name */
public Circle(double newRadius, String n) {
radius = newRadius;
cirName = n;
numberOfObjects++;
}
/** Return numberOfObjects */
public static int getNumberOfObjects() {
return numberOfObjects;
}
/** Return the area of this circle */
public double getArea() {
return radius * radius * [Link];
}
public void bigRadius(Circle c)
{
if([Link]() > [Link])
[Link]([Link]()+" has bigger radius");
else
[Link]([Link]()+" has bigger radius");
}
public void setData(double r, String n){
radius = r;
cirName = n;
}
public double getRadius() {
return radius; }
public String getName() {
return cirName;}
/**
*passing object to methods
*/
public class testCircle
{
public static void main()
{
Circle circle1 = new Circle(10, "Abu");
Circle circle2 = new Circle(2, "John");
[Link]("Area of circle belongs to "
+[Link]()
+ " is " + [Link]());
[Link]("Area of circle belongs to "
+[Link]()
+ " is " + [Link]());
[Link](circle2);
}
}
OBJECT AS METHOD TYPE
Instead of using primate data types or void, object can be also used as a method type. For
example:
public Student determineHighest (Student stud1, Student stud2)
{
if ([Link]() > [Link]()
return stud1; //return the object
else
return stud2; //return the object
}
ARRAY
A collection of data values
In Java, an array is an indexed collection of data values of the same type
Arrays of primitive data types – as mentioned erlier
Passing array as parameter to method; only its reference is passed. A copy of the array is
not created in the method. Example of method that receives array as parameter
public int FindSmall (int[] number)
{
int small = number[0]];
for (int j=0; j< [Link]; j++)
{ if (number[j] < small;
small = number[j];
else
small = small;
}
return small;
}
ARRAY OF OBJECTS
• Can use arrays to manipulate objects
Syntax: (creating array name with number of objects)
class_name[] object_name = new class_name[size];
Example: create array named array1 with N objects of type T
T[] array1 = new T[N]
Instantiate object (syntax)
for (int index=0; index <object_name.length; index++)
object_name[index] = new class_name();
Example: based on the above; Can instantiate array1 as follows:
for(int j=0; j <[Link]; j++)
array1[j] = new T();
Array of String Objects
String[] nameList = new String[5];
nameList[0] = "Amanda Green";
nameList[1] = "Vijay Arora";
nameList[2] = "Sheila Mann";
nameList[3] = "Rohit Sharma";
nameList[4] = "Mandy Johnson";
Clock[] arrivalTimeEmp = new Clock[100];
Instantiating Array Objects
for (int j = 0; j < [Link]; j++)
arrivalTimeEmp[j] = new Clock();
arrivalTimeEmp[49].setTime(8, 5, 10);
COMPOSITE OBJECTS (NESTED)
Refers to has-a relationship
Where the declaration of an object is inside the other object/class as an attribute
Example (4 classes : 2 + 1 + 1 )
1. Class Date (file)
public class Date
{
private int dMonth; //variable to store the month
private int dDay; //variable to store the day
private int dYear; //variable to store the year
//Default constructor
//The instance variables dMonth, dDay, and dYear are set to
//the default values.
//Postcondition: dMonth = 1; dDay = 1; dYear = 1900;
public Date() {
dMonth = 1;
dDay = 1;
dYear = 1900;
}
//Constructor to set the date
//The instance variables dMonth, dDay, and dYear are set
//according to the parameters.
//Postcondition: dMonth = month; dDay = day;
// dYear = year;
public Date(int month, int day, int year) {
dMonth = month;
dDay = day;
dYear = year;
}
//Method to set the date
//The instance variables dMonth, dDay, and dYear are set
//according to the parameters.
//Postcondition: dMonth = month; dDay = day;
// dYear = year;
public void setDate(int month, int day, int year) {
dMonth = month;
dDay = day;
dYear = year;
}
//Method to return the month
//Postcondition: The value of dMonth is returned.
public int getMonth() {
return dMonth;
}
//Method to return the day
//Postcondition: The value of dDay is returned.
public int getDay() {
return dDay;
}
//Method to return the year
//Postcondition: The value of dYear is returned.
public int getYear() {
return dYear;
}
//Method to return the date in the form mm-dd-yyyy
public String toString() {
return (dMonth + "-" + dDay + "-" + dYear);
}
}
2. Class Person (file)
public class Person
{
private String firstName; //store the first name
private String lastName; //store the last name
//Default constructor;
//Initialize firstName and lastName to empty string
//Postcondition: firstName = ""; lastName = "";
public Person() {
firstName = "";
lastName = "";
}
//Constructor with parameters
//Set firstName and lastName according to the parameters
//Postcondition: firstName = first; lastName = last;
public Person (String first, String last) {
firstName = first;
lastName = last;
}
//Method to output the first name and last name
//in the form firstName lastName
public String toString() {
return (firstName + " " + lastName);
}
//Method to set firstName and lastName according to
//the parameters
//Postcondition: firstName = first; lastName = last;
public void setName(String first, String last) {
firstName = first;
lastName = last;
}
//Method to return the firstName
//Postcondition: the value of firstName is returned
public String getFirstName() {
return firstName;
}
//Method to return the lastName
//Postcondition: the value of lastName is returned
public String getLastName()
{
return lastName;
}
}
3. Class PersonalInfo (file)
public class PersonalInfo
{
private Person name; //composite object
private Date bDay; //composite object
private int personID;
//Default constructor
//Instance variables are set to the default values
//Postcondition: firstName = ""; lastName = "";
// dMonth = 1; dDay = 1; dYear = 1900;
// personID = 0;
public PersonalInfo()
{
name = new Person();
bDay = new Date();
personID = 0;
}
//Constructor with parameters
//Instance variables are set according to the parameters
//Postcondition: firstName = first; lastName = last;
// dMonth = month; dDay = day; dYear = year;
// personID = ID;
public PersonalInfo(String first, String last, int month,
int day, int year, int ID)
{
name = new Person(first,last);
bDay = new Date(month,day,year);
personID = ID;
}
//Method to set the personal information
//Instance variables are set according to the parameters
//Postcondition: firstName = first; lastName = last;
// dMonth = month; dDay = day; dYear = year;
// personID = ID;
public void setpersonalInfo(String first, String last, int month,
int day, int year, int ID)
{
[Link](first,last);
[Link](month,day,year);
personID = ID;
}
//Method to return the string containing personal information
public String toString()
{
return ("Name: " + [Link]() + "\n"
+ "Date of birth: " + [Link]() + "\n"
+ "Personal ID: " + personID);
}
}
4. Class TestProgComposition (application program)
public class TestProgComposition
{
public static void main(String[] arg)
{
PersonalInfo newStudent = new PersonalInfo("William",
"Jordan", 8, 24, 1963,
555238911);
[Link]([Link]());
}
}