Chapter 3 (Basic Concept of Class)

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 40

Chapter 3 Basic Concept of Classes

CHAPTER 3: BASIC CONCEPT OF CLASSES

Objectives:
1. Discuss about class concept.
2. Learn about fields, methods of a class and access levels.
3. Distinguish between user-defined and predefined methods.
4. Explore how classes are implemented.
5. Examine constructor, accessor and mutator methods.
6. Examine the method toString()
7. Learn about wrapper classes - Integer, Double, Boolean, Character

3.1 Class concept

A class is code that describes a particular type of object. It specifies the data that an object can
hold (Object’s field/attributes) and the action that the object can perform (object’s method).
A Java class is a specific category of objects and it specifies the type of data (attributes) that the
objects can have and the actions (methods) that the object can do.
A class should represent a single concept from the problem area, such as mathematics, science
or business.
Examples of classes:
 From mathematical area : Shape (Circle, Rectangle)
 From scientific area : Vehicle (Car, Truck)
 From business area : Product (Food, Beverage),
Inventory (Stationery, Book)
 From general area : Person (Student, Employee),
Furniture (Dining set, Bedroom set)
The first step towards designing a class is a process that is called abstraction.
Abstraction is a process of finding the important set of features for a class.
The next step in designing a class is known as encapsulation.
Encapsulation is a process of hiding an object’s data and providing methods for accessing the data.

3.1.1 General Java Program Form

1
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

 There are two general forms of Java classes:


o Driver classes
o Object Classes
 Driver classs:
o Contain a main method
 A main method is necessary to run a Java program.
 The main method may include instances from an object class
 Variables
 Loops, conditional statements
 Other programming logic
o Can also contain other static methods
 Object Classes
o Are classes that define objects to be used in a driver class
o Can be found in the Java API or created by you
o Example : String, BankAccount, Student, Rectangle

The Java API is a library of a packages and object classes that are already written and are
available for use in your programs.

3.2 Class definition

The general syntax for defining a class is:

modifier class className


{
//classMembers

modifier - used to alter the behavior of the class (public).


className - a name for the class (user-defined type).
classMembers - consist of named constants, variable declarations and methods.

The following are some facts about members of a class:


 If a member of a class is a named constant, you declare it just like any other named constant.
 If a member of a class is a variable, you declare it just like any other variable.
 If a member of a class is a method, you define it just like any other method.

2
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

 If a member of a class is a method, it can (directly) access any member of the class – data
members and methods. Therefore, when you write the definition of a method, you can directly
access any data member of the class (without passing it as a parameter).

In Java, class is a reserved word, and it defines only a data type; no memory is allocated. It
announces the declaration of a class.

3.3 Data members

In Java, the data members of a class are also called fields.


The members of a class are usually classified into 3 categories (also called as visibility modifiers):
private, public, protected and default.
Private Only access from inside the same class
public Allows access from anywhere
protected data member of a super class are directly accessible in a subclass
(derived class) and still prevent its direct access outside the class
Default Allows access inside the class, subclass, or other classes of the
(not same package as the modifier.
specified)

3.4 Basic types of methods

Method that that can be performed on an object. They are also referred to as instance methods.
Methods may return an object’s variable values (sometimes called functions) or they may change
an object’s variable values.

There are 3 basic types of methods


1. constructor
2. storer/mutator/set
3. retriever/accessor/get

A method defined in an object is called instance method.


A method is called (invoked) by using a selection operator (.).
General syntax for calling a instance method:
objectName.methodName ();

Using methods has several advantages:


3
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

 While working on one method, you can focus on just the part of the program and construct it,
debug it, and perfect it.
 Different people can work on different methods simultaneously.
 If a method is needed in more than one place in a program, or in different programs, you can
write it once and use it many times.
 Using methods greatly enhances the program’s readability because it reduces the complexity
of the method main.

Methods are often called modules.


Methods are like a miniature program where you can put them together to form a large program.

3.4.1 CONSTRUCTOR
Classes are constructs that define objects of the same type.
A Java class uses variables to define data fields and methods to define behaviors.
Additionally, a class provides a special type of methods, known as constructors, which are
invoked to construct objects from the class.
In addition to the methods necessary to implement operations, every class has special types of
methods called constructors, which will be executed automatically when the new operator is
carried out and it must be called every time an object is created.
Constructors are used to guarantee that the instance variables of the class initialize to specific
values.
There are 2 types of constructors: with parameters and without parameters.
The constructor without parameters is called default constructor.
Constructors have the following properties:
 The name of a constructor is the same as the name of the class.
 A constructor, even though it is a method, has no type. That is, it is neither a value-returning
method nor a void method.
 A class can have more than one constructor. However, all constructors of a class have the
same name. That is, the constructors of a class can be overloaded.
 If a class has more than one constructor, the constructors have a different number of formal
parameters. However, if the number of formal parameters is the same, then the data types
of the formal parameters, in the order you list, must differ in at least one position. In other
words, any two constructors must have different signatures.
 Constructors execute automatically when class objects are instantiated. Because they have
no types, they cannot be called like other methods.

4
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

 If there are multiple constructors, the constructor that executes depends on the type of values
passed to the class object when the class object is instantiated.

*If you do not include any constructor in a class, then Java automatically provides the
default constructor.

A constructor method is unique in Java because:

 The method creates an instance of the class.


 Constructors always have the same name as the class and do not declare a return
type.

Default Constructor (Without Parameters)

Create a constructor without parameter (the parenthesis is empty) means this constructor
initializes the numeric class variables to zero and object variables to null.
The syntax for default constructor is:
public className ()
{
statements;
}
Example: Consider the following definition of default constructor:
public Student ()
{ name = “”;
idNumber = “”;
cgpa = 0.00;
}
Example of calling statement:
Student stud = new Student ();
Consider the Example above (Class TestStudent):
 Initially, all data that are in the class Student are not defined with values when they were first
created (constructed).
 The data in object stud above are defined when the setData() method is called.
 A default constructor is automatically included in the class TestStudent when an object of the
class Student is created using operator new.

5
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

Constructor with Parameters


There are also times when we would like to simply initialize the data into the object while creating
it.
We can supply the values to the constructor as arguments, and this type of constructors are
called constructors with arguments.
The syntax for constructor with parameters is:
public className (parameters1, parameters2,.., parametersN)
{
statements;
}

Example: Consider the following definition of constructor with parameters.


public Student (String str, String id, double cgpa)
{
name = str;
idNumber = id;
this.cgpa = cgpa ;
}

Example of calling statement:


Student stud = new Student (“Siti”, ITM1232, 3.00);

Constructors with arguments work in a similar manner like the setData() methods.
The purpose of a constructor is to initialise an object into a valid state.
When both default constructor and constructor with parameters are defined in the same class,
these constructors are said to have been overloaded.
Overloading a method is the situation when more than one methods of the same name are
defined differently in the same class.

Example: The program using overloaded constructors (TestStudent2.java)

public class TestStudent2


{
public static void main (String args [])
{
//To create a new class object named stud1,
//default constructor is included
Student2 stud1 = new Student2();

6
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

//To create a new class object named stud2,


//constructor with parameters is included
Student2 stud2 = new Student2 ("Liza", 50502873, 3.33);

//To retrieve data from the Student2 class by using


//the instance methods
System.out.println ("Name: " + stud2.getName ()
+ "\nID Number: " + stud2.getID ()
+ "\ncgpa: " + stud2.getCGPA ());
}

Example: The Student Class (Definition of class members – Student2.java)

public class Student2


{
private String name; //the student’s name
private int idNumber; //the ID number
private double cgpa; //the cgpa

//default constructor
public Student2()
{

//overloaded constructor
public Student2(String str, int id, double cgpa)
{
name = str;
idNumber = id;
this.cgpa = cgpa;
}

//To store Student with data passed as parameters


public void setData (String str, int id, double studCgpa)
{
name = str;
idNumber = id;
cgpa = studCgpa;
}

//to retrieve the Student’s name


public String getName ()
{
return name;
}

//to retrieve the Student’s ID


public int getID ()
{
return idNumber;
}
7
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

//to retrieve the Student’s CGPA


public double getCGPA ()
{
return cgpa;
}
}

3.4.2 Mutator Methods

Mutator is a method of a class that modifies the value(s) of the data member(s).
Typically, mutator methods begin with the word set.
It is different from a constructor because it can be invoked as many times as needed through out
the program execution.
The mutator methods are also known as set methods or storer because they change an object’s
state. For example, from an unknown or undefined object, an object has a known data stored in
it.
The mutator methods are used to sending input into objects or when an objects need to be stores
with new or different values.
The example of mutator method is shown in the Student class:

//To store a Student with data passed as parameters


public void setData (String str, int id, double studCgpa)
{
name = str;
idNumber = id;
cgpa = studCgpa;
}

The differences between constructor and setData() method:

Constructor setData() method

Same name as the class name Different name from the class name

Has no return type Has a void type

Can be called more than once in a


Called only once in the program
program

8
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

3.4.3 Accessor Methods

Accessor is a method of a class that only accesses (that is, does not modify) the value(s) of the
data member(s).
Typically, the instance variables of a class are declared private so that the user of a class does
not have direct access to them.
Accessor methods are typically, begin with the word get.
Accessor methods are also known as get methods or retriever because they retrieve (take
back) the value stored in an object without changing the object’s state.
Accessor methods a commonly (but not restricted to) used in displaying an object’s data and
computation of instructions involving objects.
The example of accessor methods are shown in the Student class:

//to retrieve the Student’s name


public String getName ()
{
return name;
}

//to retrieve the Student’s ID


public int getID ()
{
return idNumber;
}

//to retrieve the Student’s CGPA


public double getCGPA ()
{
return cgpa;
}

9
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

UML Diagram
Example: class Student.
Example: A UML Diagram of the class Student
Student
- name : String
- idNumber : int
- CGPA : double
Indicator:
+ Student( )
-  private access level
+ setData (String, int, double) : void
+  public access level
+ getName ( ) : String
+ getID ( ) : int
+ getCGPA ( ) : double

Object-oriented programs let us define our own class and build different methods tailored to our
programming needs.

10
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

3.5 Methods definition

Methods are commonly used to break a problem down into small manageable pieces. This is called
divide and conquer.

Methods simplify programs. If a specific task is performed in several places in the program, a
method can be written once to perform that task, and then be executed anytime it is needed. This
is known as code reuse.

Two categories of user-defined methods:


 Value-returning methods
 Void methods

To use a method in a program, you must know:


 Name of method
 Number, type, order of parameters
 Data type of value returned
 Code required to accomplish the task

Formal parameter: declared in method header


Actual parameter: listed in call to a method

Method definition
 A method definition consists of the method’s header and method’s body.
 A method header consists of the method’s type, name and parameters.
 A method with no arguments has no parameters in its header.
 A method that has no return value is called a void method.

 Method syntax:
modifier(s) returnType methodName (formal parameter list)
{
statement(s)
}

modifier(s) : visibility of method


returnType : type of value method returns
methodName : Java identifier

11
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

 Two Parts of Method Declaration:


public static void displayMesssage() Header
{
System.out.println(“Hello”); Body
}

 Parts of a Method Header


Method Modifier Return Type Method Name Parentheses

public static void displayMessage ( )


{
System.out.println(“Hello”);
}

 Method modifiers
1. public - method is publicly available to code outside the class
2. static - method belongs to a class, not a specific object.

 Return type - void or the data type from a value-returning method


 Method name - name that is descriptive of what the method does
 Parentheses - contain nothing or a list of one or more variable declarations if the method is
capable of receiving arguments.

 Syntax of a formal parameter list:


(dataType identifier, dataType identifier,………………….)

 Method call syntax:


methodName (actual parameter list);

 return statement
 Value-returning methods use return statement to return a value
 Pass value back when method completes
 Syntax: return expr; // expr is a variable, constant, or expression
 return is a reserved word
 Method immediately terminates and control goes back to caller after return statement

12
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

 Value-Returning Method
 Local variable: variable is local to a method
 Example:
public static double square(double num)
{
return num * num;
}
 Void Method
 Value-returning method returns one value
 May want to return no value or many values
 Void method returns no value.
 Example:
public static void printNum(double x)
{
System.out.print(x);
}

 Flow of (Method) Execution


 Methods can appear in any order
 Method main executes first
 Other methods execute when called
 Method call transfers control to first statement in method body
 After method finishes, control passed back to caller
 After value-returning method executes, return value replaces method call statement in caller

13
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

Parameter passing

public static void main (String[] args)


{
displayValue(5); The argument 5 is
copied into the
displayValue(5, 2.5); parameter variable num

System.out.println(“End of methods”);
}
The argument 5 is
public static void displayValue(int num) copied into the
{ parameter variable num1
System.out.println(“The value = ” + num);
}

public static void displayValue(int num1, double num2)


{
double sum;
sum = num1 + num2;
System.out.println(“The sum = ” + sum);
} The argument 2.5 is
copied into the
Output : The value = 5 parameter variable num2
The sum = 7.5
End of methods

Return Values
public static void main (String[] args)
{
int value1 = 20, value2 = 40;
The argument 20 is
total = sum(value1, value2);
copied into the parameter
Return value of variable num1
System.out.println(“Total :” +total);
result = 60 to }
variable total.
public static int sum(int num1, int num2)
{
int result;
result = num1 + num2; The argument 40 is
return result; copied into the parameter
} This expression must be of variable num2
the same data type as the
return type
Return type - The return
statement causes the method to
end execution and it returns a Output : Total : 60
value back to the statement that
called the method.

14
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

Method Calls

public static void main (String[]args)


{
int i=5;
int j=2;

int k = max(i,j);
System.out.print(“(“The maximum ” +i +“and” +j +“is” +k);
System.out.println();
System.out.print(“The maximum ” +i +“and” +j +“is” +(max(i,j));
}

public static int max(int num1, int num2)


{
int result;
if(num1 > num2)
{
result = num1;
}
else
{
result = num2;
}
return result;
}
Output: The maximum 5 and 2 is 5
The maximum 5 and 2 is 5

Duration of identifier
 The duration of identifier refer to the “lifetime” of a variable declared in the body of a method.
 An identifier that is declared in a method exists while the method is executed.
 When a method finished its execution the identifier is no longer in existence.

Scope rules
 A method’s scope of identifiers refers to the area in which the identifiers are recognizable.
 An identifier declared in a method is only known to the method that declared it and is not known
to other methods.
 Therefore, an identifier with the same name but declared in different method are two different
identifiers.

Method with parameters


 A parameter in a method declaration is an item of information that is specified to the method.
 A value is passed to a method through parameter passing.
 When a method is called, and argument is passed to the method.
 The actual value that is received by the method is stored in the parameter.
15
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

 There are rules for parameter passing:


 The number of arguments must correspond to the number of parameters.
 The type of each corresponding argument must be compatible (same) with the type of the
parameters.
 In an object-oriented program, passing information to an object is done by calling a method.

Example 1 : Kilometers to Miles

import javax.swing.*;

public class KmToMiles


{
public static void main(String[] args)
{
// constants
final double MILES_PER_KILOMETER = 0.621;

// Variables
String str; // String version of km before conversion to double.
double kilometers; // Number of kilometers.
double miles; // Number of miles.

// Input
kmStr=JOptionPane.showInputDialog(null,"Enter kilometers.");
kilometers = Double.parseDouble(str);

// Computation
miles = kilometers * MILES_PER_KILOMETER;

// Output
JOptionPane.showMessageDialog(null, kilometers + " kilometers is "
+ miles + " miles.");
}
}

Output:

16
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

Example 2 : Kilometers to Miles with Method

import javax.swing.*;
public class KmToMilesMethod
{
public static void main(String[] args)
{
//method calls for user enter kilometers
double km = inputData();

//method calls for convert kilometer to miles


double mi = convertKmToMi(km);

//method calls for display output


displayData(km,mi);
}

public static double inputData()


{
//Input
String kmStr = JOptionPane.showInputDialog(null, "Enter kilometers.");
double k = Double.parseDouble(kmStr);
return k;
}
public static double convertKmToMi(double kilometers)
{
// Assume there are 0.621 miles in a kilometer.
double miles = kilometers * 0.621;
return miles;
}
public static void displayData(double a, double b)
{
//Output
JOptionPane.showMessageDialog(null,a +" kilometers is " + b + " miles.");
}
}

17
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

Example: A java application with class methods calls


import java.util.*;
public class ClassMethod
{
public static void main(String[]args)
{
int num1, num2, sum;

//get input for two numbers


num1 = Number.get();
num2 = Number.get();

//compute the sum of the two numbers


sum = Number.add(num1,num2);

//print num1,num2 and sum


System.out.println(num1 +" + " +num2 +" = " +sum);

System.exit(0);
}
}

class Number
{
static Scanner input = new Scanner(System.in);

public static int get()


{
System.out.print("Type a number : ");
int num = input.nextInt();
return num;
}

public static int add(int a, int b)


{
int result;
result = a + b;
return result;
}
}

18
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

Example: A Java application with instance methods that has no argument or return value

public class InstanceMethod


{
public static void main(String[]args)
{
Greeting message = new Greeting();

message.welcome();

for(int i=0; i<3; i++)


{
message.hello();
message.bye();
}
}
}
class Greeting
{
public void hello()
{
System.out.println("HELLO");
}

public void welcome()


{
System.out.println("WELCOME");
}

public void bye()


{
System.out.println("GOOD BYE");
}
}

19
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

Example: A Java application with a method that has parameters

Employees in a small company receive their salary weekly. They are paid their hourly
for each hour worked. How ever if they worked more than 40 hours per week, they are
paid overtime 1.5 times of their regular wage.
Write a Java Application that will ask for input an employee’s hourly salary and the total
hours worked in a week. Compute and print the salary for the week.

import javax.swing.*;

public class MethodWithParameter


{

public static void main(String[]args)


{
Employee worker = new Employee();

String str;
double hourlyWage;
int hoursWorked;

str=JOptionPane.showInputDialog("Enter the hourly wage:");


hourlyWage = Double.parseDouble(str);

str=JOptionPane.showInputDialog("Enter the total hours worked:");


hoursWorked = Integer.parseInt(str);

worker.set(hourlyWage, hoursWorked);

JOptionPane.showMessageDialog(null,"Hourly wage : "+worker.wage());


+"\nHours worked : " +worker.hours()
+"\nTotal salary : " +worker.salary());
System.exit(0);
}
}

class Employee
{
double wage;
int hours;
double salary;
public void set(double a, int b)
{
wage = a;
hours = b;
}

public double wage()


{
return wage;
}

public int hours()


{
20
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

return hours;
}

public double salary()


{
if(hours <= 40)
salary = hours * wage;
else
salary = 40 * wage + (hours - 40) * (1.5 * wage);

return salary;
}
}

21
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

Example: A Java application with methods that have parameters

import java.util.*;
public class MethodWithParameter2
{
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);

Sorter number = new Sorter();

int n1, n2, n3;

System.out.print("Enter a number : ");


n1 = input.nextInt();

System.out.print("Enter a number : ");


n2 = input.nextInt();

System.out.print("Enter a number : ");


n3 = input.nextInt();

number.setData(n1,n2,n3);

System.out.println();

System.out.println("Initial list of numbers :");


number.print();

System.out.println();

System.out.println("Smallest : " +number.small()


+"\nLargest : " +number.large()
+"\nAverage :" +number.average());

System.out.println();

System.out.println("After all numbers are doubled : ");


number.multiply(2);
number.print();

System.exit(0);
} }
class Sorter
{
int first;
int second;
int third;

public void setData(int a, int b, int c)


{
first = a;
second = b;
third = c;
}
22
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

public int small()


{
if(first < second && first < third)
return first;
else if(second < first && second < third)
return second;
else
return third;
}

public int large()


{
if(first > second && first > third)
return first;
else if(second > first && second > third)
return second;
else
return third;
}

public double average()


{
double sum;
sum = (double)(first + second + third);
return (sum/3);
}

public void multiply(int x)


{
first *= x;
second *= x;
third *= x;
}

public void print()


{
System.out.println("First number = " +first
+"\nSecond number = " +second
+"\nThird number = " +third);
}
}

23
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

3.6 Static fields and methods


The modifier static in the heading specifies that the method can be invoked by using the name of
the class.
Similarly, if a data member of a class is declared using the modifier static, it can be accessed by
using the name of the class.
The following are some of the examples of static methods and package:

1) Math.pow (5, 3) means that, the heading of the method pow of the class Math is:

public class Math


{
public static double pow (double base, double exponent)
{
}
}

2) JOptionPane.showInputDialog (“Enter your name: “); means that, the heading


of the method showInputDialog of the class JOptionPane is:

public class JOptionPane


{
public static String showInputDialog (String str)
{
}
}

3) import static java.lang.Math.*; //static package


To use the method pow of the class Math, we used the following expression:
pow (5, 3);

The following Java programs describe how the static fields and method are defined in the class
definition and how they are invoked at the driver method:

1) Class definition named Illustrate:

public class Illustrate


{
private int x; //instance variable
private static int y; //static variable (field)
public static int count; //static variable (field)

24
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

//Default constructor, Postcondition: x = 0;


public Illustrate()
{
x = 0;
}

//Constructor with parameters, Postcondition: x = a;


public Illustrate (int a)
{
x = a;
}

//Method to set x, Postcondition: x = a;


void setX (int a)
{
x = a;
}

//Method to return the values of the instance and static


//variables as a String. The String returned is used
//by the methods print, println, or printf, to
//print the values of the instance and static variables.
//The values of x, y, and count are returned as a String.
public String toString ()
{
return (“x = “ + + “, y = “ + y + “, count = “ + count);
}

//Method to increment the value of the private static member y.


//Postcondition: y is incremented by 1.
public static void incrementY () //static method
{
y++;
}
}

25
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

Further, suppose that you have the following declaration:


Illustrate obj1 = new Illustrate ();

The reference variable obj1 can access any public member of the class Illustrate.
Because the method incrementY is static and public, the following statement is legal:
Illustrate.incrementY();

Similarly, because the data member count is static and public, the following statement is legal:
Illustrate.count++;

Consider the following statements: Illustrate obj1 = new Illustrate (3);


Illustrate obj2 = new Illustrate (5);

y 0

count 0

Obj1 x 3 Obj2 x 5

Consider the following statements:


Illustrate.incrementY();
Illustrate.count++();

After these statements execute, the objects and static members are shown below:

y 1

count 1

Obj1 x 3 Obj2 x 5

26
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

2) Driver method: Trace the output for the following program:

//This program illustrates how static members of a class work.


public class StaticMembers
{
public static void main (String[] args)
{
Illustrate obj1 = new Illustrate (3);
Illustrate obj2 = new Illustrate (5);

Illustrate.incrementY();
Illustrate.count++;
System.out.println (obj1);
System.out.println (obj2);

System.out.println (“*** Increment y using obj1 ***”);


obj1.incrementY();
obj1.setX(8);
System.out.println (obj1);
System.out.println (obj2);

System.out.println (“*** Increment y using obj2 ***”);


Obj2.incrementY();
Obj2.setX(23);
System.out.println (obj1);
System.out.println (obj2);
}
}

27
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

Overloaded Method

Method can share the same name as long as


- They have a different number of parameters (Rule 1) or
- Their parameter are different data types when the number of parameters is the same
(Rule 2)

Java compiler determines which method to call/invoke based on the method signature.
Example:

- If max() method with int parameters is called, the max() method that expects int
parameters will be invoked. If max() method with double parameters is called, the
max() method that expects double parameters will be invoked.

28
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

The same rules apply for the overloaded constructors.

29
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

3.7 PRE-DEFINED CLASSES


In Java, predefined methods are organized as a collection of classes, called class libraries.
In general, to use the predefined methods of a class in a program, you must import the class from
the package containing the class (already discussed in the Chapter 1).
Methods are called by writing the name of the class (or object) and the name of the method
followed by the argument (or list of arguments, separated by a comma) in a set of parenthesis.
General syntax for calling a class method:
className.methodName ();

The Method toString


The method toString is used to convert an object to a String object and it is a public value-returning
method.
It does not take any parameters and returns the address of a String object.
The methods print, println, and printf output the string created by the method toString.
The default definition of the method toString creates a string that is the name of the object’s class,
followed by the hash code of the object.

Example: Consider the following definition of the class Clock:


public class Clock
{
private int hr;
private int min;
private int sec;

public Clock ()
{
setTime (0, 0, 0)
}
public String toString ()
{
String str = “”;
if (hr < 10)
str = “0”;
str = str + hr + “:”;

if (main < 10)


str = str + “0”;
str = str + min + “:”;

if (sec < 10)


str = str + “0”;
str = str + sec;
}
}

30
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

Further, suppose that you have the following declaration:


Clock myClock = new Clock ();

If the values of the instance variables hr, min, and sec of myClock are 8, 25 and 56, respectively,
then the output of the statement:
System.out.println (myClock);
is:
08:25:56
You can see that the method toString is quite useful for outputting the values of the instance
variables.

The Method equals()


With primitive data types, we have only one way to compare them, but for objects (reference
data type), we have two ways to compare them.
String comparison is done by a method equals ().

Example 1: Primitive data type

int num1, num2;


num1 = 17;
num2 = 17;

if (num1 == num2)
System.out.println (“They are equal”);
else
System.out.println (“They are not equal”);

Output: They are equal

Refer to the
same value = 17

17 17

num1 Num2

31
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

Example 2: Objects (Reference data type)

Case A: Two variables refer to two different objects


public class EqualsMethod
{
public static void main (String[] args)
{
String str1, str2;

str1 = new String (“Java”);


str1 str2 str2 = new String (“Java”);

if (str1 == str2)
  System.out.println (“They are equal”);

else
System.out.println(“They are not equal”);
:String :String
}
}
Java Java str1 == str2 FALSE

Output:
They are not equal

Case B: Two variables refer to the same objects (First way).

public class EqualsMethod


{
public static void main (String[] args)
{
String str1, str2;

str1 = new String (“Java”);


str1 str2 str2 = str1;

if (str1 == str2)
  System.out.println (“They are equal”);

else
System.out.println(“They are not equal”);
:String
}
}
Java str1 == str2 TRUE

Output:
They are equal

32
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

Case C: Comparison method: The equals (..) method returns true if two String objects have the
exact same sequence of characters (Second way).

public class EqualsMethod


{
public static void main (String[] args)
{

String str1, str2;

str1 str2 str1 = new String ("Java");


str2 = new String ("Java");

  if (str1.equals(str2))
System.out.println ("They are equal");

else
:String :String System.out.println ("They are not equal");

}
Java Java }

str1.equals(str2) TRUE

Output:
They are equal

3.5 PREDEFINED CLASSES

Eventually, you must learn how to define your own classes, the classes you will reuse in writing
programs.
But before you can become adapt at defining your own classes, you must learn how to use existing
classes or predefined classes.

3.5.1 String Class


A package called java.lang.* must be imported or included in the file containing a Java application.
A String is a sequence of characters that is treated as a single value.
Instances of the String class are used to represent strings in Java.
Index of first character in string is 0
Length of string: number of characters in it
String variables are reference variables
– String object an instance of class String
class String contains methods to process strings
String variable invokes String method using the dot operator, method names, arguments

String Concatenation (concat)

33
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

String s1 = “25”;
String s2= “55”;
String r = “with”;

Method / Operator Descriptions Example


operator (+) concatenates s1 and s2 r = s1 + s2; Ans: r = 2555
operator (+=) concatenates s2 to result r += s2; Ans: r = with55
concat() the same as s1 + s2 r = s1.concat (s2); Ans: r = 2555

Substrings – substring (index), substring(start, end))

String s1 = “Welcome to Java”;


Method Descriptions Example
substring(index), Returns a substring of this string from s1.substring(3);
index position start to the last Ans: come to Java
character of this string. s1.substring(17);
Ans: “”  empty string
substring(start, end)) Returns a substring of this string from s1.subString(3, 9);
index position start to end – 1. Ans: come to t

Comparisons – equals(), equalsIgnoreCase(), compareTo()

String s1 = “GOOD LUCK”;


String s2 = “good luck”;
String s3 = “GOOD LUCK”;
Method Descriptions Example
equals() Returns true if the string s1 is s1.equals(s2)
equal to s2 Ans: false
equalsIgnoreCase() Returns true if the string s1 s1.equalsIgnoreCase(s2)
matches s2, case-blind Ans: true
compareTo() Compares 2 strings character by
character.
a. Returns a negative value if s1 s1.compareTo(s2); Ans: - 32
is less than s2
s1.compareTo(s3); Ans: 0
34
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

b. Returns 0 if s1 is the same as


s3 s2.compareTo(s1); Ans: 32
c. Returns a positive value if s1
is greater than s2

Example: String s1 = “Welcome to Java”;


String s2 = s1;
String s3 = new String(“Welcome to Java”);
What are the results of the following expressions?
a. s1 == s2  true (same object)
b. s1 == s3  false (different object)
c. s1.equals(s2)  true (same content)
d. s2.equals(s3)  true (same content)

String Conversions / Replacements

String s1 = “ProGRammiNG in JAVA”;


Method Descriptions Example
trim() returns a new string formed from s1 by s1.trim()
removing white space at both ends Ans: ProGRammiNGinJAVA
replace(oldCh, returns a new string formed from s1 by s1.replace(‘m’ , ‘S’)
newCh) replacing all occurrences of oldCh with Ans: ProGRaSSiNG in JAVA
newCh
toUpperCase() returns a new string formed from s1 by s1. toUpperCase()
converting its characters to upper case Ans: PROGRAMMING IN JAVA
toLowerCase() returns a new string formed from s1 by s1. toLowerCase()
converting its characters to lower case Ans: programming in java

Finding a Character or a Substring in a String - length(), charAt()

String s1 = “Happy Birthday !!!”;


Method Descriptions Example
length() Returns the number of characters s1.length(); Ans: 18
in this string.
charAt(int index) Returns a character at the position s1.charAt(6); Ans: B
specified by index.
35
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

Finding index of character or String - indexOf(), lastIndexOf()

String s1 ="July 5, 2012 1:28:19 PM";


Method Descriptions Example
indexOf() Returns the index of the first s1.indexOf ('J'); Ans: 0
occurrence of the string specified by s1.indexOf ('2'); Ans: 8
str. If the string specified by str does s1.indexOf ("2012"); Ans: 8
not appear in the string, it returns -1. s1.indexOf ('2', 9); Ans: 1

lastIndexOf() Is the same as indexOf() but s1.indexOf ("2020"); Ans: -1


searching the string from the last s1.indexOf ("2010"); Ans: 8
index. s1.lastIndexOf ('2'); Ans: 15
s1.lastIndexOf (‘2’, 9) Ans: 8

3.5.2 JOptionPane

A package called javax.swing.* must be imported or included in the file containing a Java
application.
A class from the package named JoptionPane will be used for the input (and/or output) process.
The String class is part of the java.lang package which is automatically included during compilation

Input – the showInputDialog() method is used


 has one string parameter which is the message to be displayed to the user
 returns the string keyed in by the user and returns the null string if user cancels
String st;
st = JOptionPane.showInputDialog(“Give a number”);

 to do mathematical operations on the given data, the string returned by showInputDialog


must be converted to the required numerical data type

 the parse functions in various wrapper classes are used


int num = Integer.parseInt(st);
float nom = Float.parseFloat(st);
double x = Double.parseDouble(st);
Output – the showMessageDialog() method is used

36
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

 has one string parameter which is the message to be displayed to the user

String st;
st = “The answer is “ + num;
JOptionPane.showMessageDialog(null,st);

Input using the Scanner class


 create a Scanner object by passing an input stream to the constructor
Scanner in = new Scanner(System.in);

 use the nextInt(), nextDouble(), nextLine(), next() methods to read data typed on the
keyboard
System.out.println(“Enter an integer: “);
int num = in.nextInt();

Example: JOptionPane
Program to add two numbers given by the user

import javax.swing.JOptionPane;

class ProcessNumber
{
public static void main(String[] args)
{
String input = JOptionPane.showInputDialog("Enter first number");
int no1 = Integer.parseInt(input);

input = JOptionPane.showInputDialog("Enter second number");


float no2 = Float.parseFloat(input);

float total = no1 + no2;

JOptionPane.showMessageDialog(null,"The total is "+total);

System.exit(0);
}
}

37
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

Example: Class Scanner


Program to add two numbers given by the user

import java.util.Scanner;

class ScannerTest
{
public static void main(String []arg)
{
Scanner in = new Scanner(System.in);

int num;
int total = 0;

System.out.print("Enter an integer: ");


num = in.nextInt();

while (num>0)
{ total += num;
System.out.print("Enter an integer: ");
num = in.nextInt();
}
System.out.println("The total is: "+total);
}
}

3.5.3 Maths Class

A package called java.lang.* must be imported or included in the file containing a Java
application.
The Math class contains a collection of common mathematical functions or methods.
The Math class is available in the Java API and we can use the methods from this class to
express mathematical formulas.
Method type is data type returned by the method

Table 3.1 : Commonly used Math class methods


Named Constants

double E; E = 2.718281828459045

double PI; PI = 3.141592653589793


Argument
Method Result Description Examples
Type
int, long, int, long, abs(-67)  67
Returns the absolute
abs (x) float, float, abs(35)  35
value ( | a | ) of a.
double double abs(-75.38)  75.38

38
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

Returns the smallest ceil(56.34)  57.0


ceil (x) double double integer value that is not ceil(27.21)  28.0
less than x. ceil(-4.15)  -3.0
Returns ex, a value of the
type double, where e is exp(3)
exp (x) double double
approximately 20.085536923187668
2.7182818284590455
Returns the largest
floor (x) double double floor(65.78)  65.0
integer value less than x.
Returns the natural log(2)
log (x) double double
logarithm (base e) of x. 06931471805599453.
int, long, int, long,
Returns the larger of x max(15, 25)  25
max(x, y) float, float,
and y. max(45, 23.78)  45
double double
int, long, int, long,
Returns the smaller of x min(15, 25)  15
min(x, y) float, float,
and y. min(23.67, 14.28)  14.28
double double
Returns a value of the pow(2.0, 3.0)  8.0
pow(x, y) double double
type double which is x y. pow(4, 0.5)  2.0
int Returns a value that is round(24.56)  25
round(x) float double
long the integer closest to x. round(18.35)  18
Returns a value of the
sqrt(4.0)  2.0
sqrt (x) double double type double, which is the
sqrt(2.25)  1.5
square root of x.
cos(0)  1.0
Returns the cosine of x
cos(x) double double cos(PI / 3)
measured in radians
 0.5000000000000001
Returns the sine of x sin(0)  0.0
sin(x) double double
measured in radians sin(PI / 2)  1.0
Returns the tangent of x
tan(x) double double tan(0)  0.0
measured in radians

39
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes

3.6 WRAPPER CLASSES – Integer, Float, Double, Boolean, Character

A string consisting of only an integer or a decimal number is called a numeric string.


To perform the necessary type conversion in Java, we use different utility classes called wrapper
classes.
The name wrapper derives from the fact that these classes surround, or wrap, primitive data with
useful methods.
Type conversion is one of several methods provided by these wrapper classes.

1. To convert a String consisting of an integer to a value of the type int, we use the following
expression:
Integer.parseInt (strExpression)

For examples:
a. Integer.parseInt (“6723”); // = 6723
b. String strNum =JOptionPane.showInputDialog(“Enter a number:”);
int num = Integer.parseInt (strNum);

2. To convert a String consisting of a decimal number to a value of the type float, we use the
following expression:
Float.parseFloat (strExpression);

For examples:
a. Float.parseFloat (“34.56”);
b. String strNum =JOptionPane.showInputDialog(“Enter a number:”);
float num = Float.parseFloat (strNum);

3. To convert a String consisting of a decimal number to a value of the type double, we use the
following expression:
Double.parseDouble (strExpression);

For examples:
a. Double.parseDouble (“345.78”);
b. String strNum =JOptionPane.showInputDialog(“Enter a number:”);
double num = Double.parseDouble (strNum);

40
TSE2094 Object-oriented Programming

You might also like