Professional Documents
Culture Documents
Chapter 3 (Basic Concept of Class)
Chapter 3 (Basic Concept of Class)
Chapter 3 (Basic Concept of Class)
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
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.
1
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes
The Java API is a library of a packages and object classes that are already written and are
available for use in your programs.
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.
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.
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.
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.
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
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.
6
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes
//default constructor
public Student2()
{
//overloaded constructor
public Student2(String str, int id, double cgpa)
{
name = str;
idNumber = id;
this.cgpa = cgpa;
}
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:
Same name as the class name Different name from the class name
8
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes
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:
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
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.
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)
}
11
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes
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 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);
}
13
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes
Parameter passing
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);
}
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
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));
}
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.
import javax.swing.*;
// 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
import javax.swing.*;
public class KmToMilesMethod
{
public static void main(String[] args)
{
//method calls for user enter kilometers
double km = inputData();
17
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes
System.exit(0);
}
}
class Number
{
static Scanner input = new Scanner(System.in);
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
message.welcome();
19
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes
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.*;
String str;
double hourlyWage;
int hoursWorked;
worker.set(hourlyWage, hoursWorked);
class Employee
{
double wage;
int hours;
double salary;
public void set(double a, int b)
{
wage = a;
hours = b;
}
return hours;
}
return salary;
}
}
21
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes
import java.util.*;
public class MethodWithParameter2
{
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
number.setData(n1,n2,n3);
System.out.println();
System.out.println();
System.out.println();
System.exit(0);
} }
class Sorter
{
int first;
int second;
int third;
23
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes
1) Math.pow (5, 3) means that, the heading of the method pow of the class Math is:
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:
24
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes
25
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes
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++;
y 0
count 0
Obj1 x 3 Obj2 x 5
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
Illustrate.incrementY();
Illustrate.count++;
System.out.println (obj1);
System.out.println (obj2);
27
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes
Overloaded Method
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
29
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes
public Clock ()
{
setTime (0, 0, 0)
}
public String toString ()
{
String str = “”;
if (hr < 10)
str = “0”;
str = str + hr + “:”;
30
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes
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.
if (num1 == num2)
System.out.println (“They are equal”);
else
System.out.println (“They are not equal”);
Refer to the
same value = 17
17 17
num1 Num2
31
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes
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
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).
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
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.
33
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes
String s1 = “25”;
String s2= “55”;
String r = “with”;
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
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);
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);
System.exit(0);
}
}
37
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes
import java.util.Scanner;
class ScannerTest
{
public static void main(String []arg)
{
Scanner in = new Scanner(System.in);
int num;
int total = 0;
while (num>0)
{ total += num;
System.out.print("Enter an integer: ");
num = in.nextInt();
}
System.out.println("The total is: "+total);
}
}
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
double E; E = 2.718281828459045
38
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of Classes
39
TSE2094 Object-oriented Programming
Chapter 3 Basic Concept of 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