Вы находитесь на странице: 1из 9

CSC238-OOP

Basic concepts of classes

CHAPTER 3: BASIC CONCEPTS OF CLASSES


1.0 CREATING USER-DEFINED CLASS
Learning how to define our own classes is the first step toward mastering the skills necessary in
building large programs.
Classes we define ourselves are called user/programmer-defined classes.
The following figure shows the UML diagram for class & object.
Circle

UML Graphical notation for classes

radius: double

UML Graphical notation for fields


UML Graphical notation for methods

findArea(): double
new Circle()

new Circle()

circle1: Circle
radius = 2

circlen: Circle
...

UML Graphical notation


for objects

radius = 5

Figure 3.1 UML Diagram for class & object

Class Declaration
public class Circle {
double radius = 1.0;
public double findArea()
{
return radius * radius * 3.14159;
}//end of method
}//end of class

Object declaration
o Declaring object reference variable:
Class_Name objectReference;
Example:
Circle myCircle;
o

Creating object:

ObjectReference = new Class_Name();


Example:
myCircle = new Circle();

CSC238-OOP

Basic concepts of classes

Declaring & creating object in single step

Class_Name objectReference = new Class_Name();


Example:
Circle myCircle = new Circle();

Differences between variables of primitive data types and object types:

Primitive type

int i = 1

Object type

Circle c

reference

c: Circle
Created using
new Circle()

radius = 1

Copying variables of primitive data types and object types:


Primitive type assignment
i=j

Object type assignment


c1 = c2

Before:

After:

Before:

After:

c1

c1

c2

c2

c1: Circle

c2: Circle

radius = 5

radius = 9

Accessing object
o Referencing the objects data
objectReference.data
Example: myCircle.radius;
o

Invoking the objects method


objectReference.method
Example: myCircle.findArea();

CSC238-OOP

Basic concepts of classes

Example using object:


// Demonstrate creating object, accessing data & using method
public class TestCircle {
public static void main(String[] args) {
Circle myCircle = new Circle();

// Create a Circle object

System.out.println("The area of the circle of radius +


myCircle.radius + " is " + myCircle.findArea());
}
} // End of class TestCircle

Constructor
o A constructor with no parameters is referred to as a default constructor.
o A constructor with parameters is referred to as a parameterized/normal constructor.
o Constructors must have the same name as the class itself.
o Constructors do not have a return typenot even void.
o Constructors are invoked using the new operator when an object is created.
o Constructors play the role of initializing objects.
o Example:
public class Circle {
double radius;
public Circle() {
radius = 1.0;
}//default constructor
public Circle(double r){
radius = r;
}//parameterized constructor
public double findArea(){
return radius * radius * 3.14159;
}//end of method
}
o Example using constructor:
public class TestCircle {
public static void main(String[] args) {
Circle myCircle = new Circle(5.0);
System.out.println("The area of the circle of radius " +
myCircle.radius + " is " + myCircle.findArea());
Circle yourCircle = new Circle();
System.out.println("The area of the circle of radius " +
yourCircle.radius + " is " + yourCircle.findArea());
yourCircle.radius = 100; //modify circle radius
System.out.println("The area of the circle of radius " +
yourCircle.radius + " is " + yourCircle.findArea());
}
}

CSC238-OOP

Basic concepts of classes

Visibility Modifiers and Accessor Methods


o By default, the class, variable, or data can be accessed by any class in the same package.
o public (+) - the class, data, or method is visible to any class in any package.
o private (-) - the data or methods can be accessed only by the declaring class.
o The get/accessor/retriever and set/mutator/storer methods are used to read and modify
private properties.
o Example using the private modifier and accessor method:
In this example, private data are used for the radius and the accessor methods
getRadius() and setRadius() are provided for the clients to retrieve and modify
the radius.
public class CircleWithAccessors {
private double radius;
public CircleWithAccessors() {
radius = 1.0;
}
public CircleWithAccessors(double r) {
radius = r;
}
public double getRadius() {
return radius;
}
public void setRadius(double newRadius) {
radius = newRadius;
}

public double findArea() {


return radius * radius * 3.14159;
}
//End of class CircleWithAccessors

public class TestCircleWithAccessors {


public static void main(String[] args) {
CircleWithAccessors myCircle = new
CircleWithAccessors(5.0);
System.out.println("The area of the circle of radius " +
myCircle.getRadius() + " is " + myCircle.findArea());
// Increase myCircle's radius by 10%
myCircle.setRadius(myCircle.getRadius() * 1.1);
System.out.println("The area of the circle of radius " +
myCircle.getRadius() + " is " + myCircle.findArea());
}
}

CSC238-OOP

Basic concepts of classes

Passing objects to methods


o Passing by value (the value is the reference to the object)
o Example:
// TestPassingObject.java: Demonstrate passing objects to methods
public class TestPassingObject {
public static void main(String[] args) {
CircleWithAccessors myCircle = new CircleWithAccessors();
// Print areas for radius 1, 2, 3, 4, and 5.
int n = 5;
printAreas(myCircle, n);
System.out.println("\n" + "Radius is " +
myCircle.getRadius());
System.out.println("n is " + n);
}
/** Print a table of areas for radius */
public static void printAreas(CircleWithAccessors c, int
times) {
System.out.println("Radius \t\tArea");
while (times >= 1) {
System.out.println(c.getRadius() + "\t\t" +
c.findArea());
c.setRadius(c.getRadius() + 1);
times--;
}
}//end of main
}//end of class

2.0 USING PRE-DEFINED CLASSES


2.1 DecimalFormat Class
o Use a DecimalFormat object to format the numerical output.
o Example:
//include the import statement:
import java.text.*;

double num = 123.45789345;


DecimalFormat df = new DecimalFormat(0.000);
//three decimal places
System.out.print(num);
System.out.print(df.format(num));

123.45789345
123.458

CSC238-OOP

Basic concepts of classes

2.2 Math Class


o The Math class in the java.lang package contains class methods for commonly used
mathematical functions.
o Example:
double num, x, y;
x = ;
y = ;
num = Math.sqrt(Math.max(x, y) + 12.4);
o

Some Math class methods:


Method
exp(a)
log(a)
floor(a)
max(a,b)
pow(a,b)
sqrt(a)
sin(a)

Description
Natural number e raised to the power of a
Natural logarithm (base e) of a.
The largest whole number less than or equal to a.
The largest of a and b.
The number a raised to the power of b.
The square root of a.
The sine of a. (Note: all trigonometric functions are
computed in radians)

Table 3.8 page 113 in the textbook contains a list of class methods defined in the Math
class.

2.3 Date Class


o The Date class from the java.util package is used to represent a date.
o When a Date object is created, it is set to today (the current date set in the computer)
o The class has toString method that converts the internal format to a string.
o Example:
Date today;
today = new Date( );
today.toString( );
OUTPUT:
Fri Oct 31 10:05:18 PST 2003

2.4 SimpleDateFormat
o The SimpleDateFormat class allows the Date information to be displayed with
various format.
o Table 2.1 page 64 shows the formatting options.
o Example:
Date today = new Date( );
SimpleDateFormat sdf1, sdf2;
sdf1 = new SimpleDateFormat( MM/dd/yy );
sdf2 = new SimpleDateFormat( MMMM dd, yyyy );
sdf1.format(today);

10/31/03

sdf2.format(today);

October 31, 2003

CSC238-OOP

Basic concepts of classes

2.5 GregorianCalander Class


o Use a GregorianCalendar object to manipulate calendar information
o Example:
GregorianCalendar today, independenceDay;
today

= new GregorianCalendar();

independenceDay = new GregorianCalendar(1776, 6, 4);


//month 6 means July; 0 means January
o

This table shows the class constants for retrieving different pieces of calendar
information from Date.

Sample calendar retrieval:


GregorianCalendar cal = new GregorianCalendar();
//Assume today is Nov 9, 2003
System.out.print(Today is +
(cal.get(Calendar.MONTH)+1) + / +
cal.get(Calendar.DATE) + / +
cal.get(Calendar.YEAR));
OUTPUT:
Today is 11/9/2003

2.6 String Class


o A sequence of characters separated by double quotes is a String constant.
o There are close to 50 methods defined in the String class.
String
name =

name;
new String(Jon Java);

CSC238-OOP

Basic concepts of classes

substring
- Assume str is a String object and properly initialized to a String.
- str.substring( i, j ) will return a new string by extracting characters
of str from position i to j-1 where 0 i length of str, 0 j length of str, and
i j.
- If str is programming, then str.substring(3, 7) will create a new string whose
value is gram because g is at position 3 and m is at position 6.
- The original string str remains unchanged.
- Example:
String text = Espresso;
text.substring(6,8);
text.substring(0,8);
text.substring(1,5);
text.substring(3,3);
text.substring(4,2);

so
Espresso
spre

error

length
- Assume str is a String object and properly initialized to a string.
- str.length( ) will return the number of characters in str.
- If str is programming , then str.length( ) will return 11 because there are 11
characters in it.
- The original string str remains unchanged.

indexOf
- Assume str and substr are String objects and properly initialized.
- str.indexOf( substr ) will return the first position substr occurs in str.
- If str is programming and substr is gram , then str.indexOf(substr ) will
return 3 because the position of the first character of substr in str is 3.
- If substr does not occur in str, then 1 is returned.
- The search is case-sensitive.
- Example:
String str;
str = I Love Java and Java loves me. ;
str.indexOf( J )
str2.indexOf( love )
str3. indexOf( ove )
str4. indexOf( Me )

7
21
3
-1

charAt
- Individual characters in a String accessed with the charAt method.
- Example:
String name = "Sumatra";
name.charAt(3);

CSC238-OOP

Basic concepts of classes

equals
- Determines whether two String objects contain the same data.
- Example:
String
String
String
String

s1
s2
s3
s4

=
=
=
=

Hello;
hello;
new String(hello);
new String(hello);

s1.equals(s2);
s2.equals(s3);
s3.equals(s4);
o

false
true
true

equalsIgnoreCase
- Determines whether two String objects contain the same data, ignoring the case of
the letters in the String.
- Example:
String s1 = Hello;
String s2 = hello;
s1.equalsIgnoreCase(s2);

true

Other useful String operators:

Method
compareTo
trim
valueOf
startsWith
endsWith

Meaning
Compares the two strings
str1.compareTo(str2)
Removes the leading and trailing spaces
str1.trim()
Converts a given primitive data value to a String
String.valueOf(123.4567)
Return true if a String starts with a specified prefix string.
str1.startsWith(str2)
Returns true if a string ends with a specified suffix string.
str1.endsWith( str2 )

Reference:
Liang, Y. Daniel, Introduction to Java Programming, 8 th Edition, Pearson, 2011.
Wu, C. Thomas, An Introduction to Object Oriented Programming with Java, 4th Edition, Mc Graw Hill, 2006.

Вам также может понравиться