0% found this document useful (0 votes)
30 views

Chap 2 Define Ur Own Class

Uploaded by

pjssssso
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Chap 2 Define Ur Own Class

Uploaded by

pjssssso
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 77

Defining Your Own Classes

After you have read and studied this chapter, you should be able to

• Define a class with multiple methods and data members


• Differentiate the local and instance variables
• Define and use value-returning methods
• Distinguish private and public methods
• Distinguish private and public data members
• Pass both primitive data and objects to a method
You will learn about:
1. Create classes & objects.
2. Variables in OOP (data member, argument, parameter & local
variable).
• private & public (Accessibility Modifiers).
• General syntax for data member & method declaration.
• Matching Arguments & Parameters.
3. set & get method ( mutator & accessor)
4. Constructor
5. Matching Arguments & Parameters.
6. Overloaded Methods
Why Programmer-Defined Classes
• Using just the standard classes (String, Jframe) will not meet all of our
needs. We need to be able to define our own classes customized for
our applications.
• 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 programmer-defined classes.
First example - the Definition of the
Bicycle Class
class Bicycle {
// Data Member
private String ownerName;
//Constructor: Initialzes the data member
public Bicycle( ) {
ownerName = "Unknown";
}
//Returns the name of this bicycle's owner
public String getOwnerName( ) {
return ownerName;
}
//Assigns the name of this bicycle's owner
public void setOwnerName(String name) {
ownerName = name;
}
}
First Example: Using the Bicycle Class
class BicycleRegistration {
public static void main(String[] args) {
Bicycle bike1, bike2; //Create instances of class Bicycle
String owner1, owner2;

bike1 = new Bicycle( ); //Create and assign values to bike1


bike1.setOwnerName("Adam Smith");

bike2 = new Bicycle( ); //Create and assign values to bike2


bike2.setOwnerName("Ben Jones");

owner1 = bike1.getOwnerName( ); //Output the information


owner2 = bike2.getOwnerName( );

System.out.println(owner1 + " owns a bicycle.");

System.out.println(owner2 + " also owns a bicycle.");


}
}
Object Declaration
• Once class has been defined, we can create an instance of class.

<class name> <object name> = new <keyword> <constructor> ();

Note: There’s are two ways to declare an object.

<class name> <object name> ;


<object name> = new <keyword> <constructor> ();
Multiple Instances Creation
• Once the Bicycle class is defined, we can create multiple instances.

Bicycle bike1 = new Bicycle( );


Bicycle bike2 = new Bicycle( );

< or >
Bicycle bike1, bike2;
bike1 = new Bicycle( );
bike2 = new Bicycle( );
The Program Structure and Source
Files
BicycleRegistration Bicycle

There are two source files.


Each class definition is
stored in a separate file.
BicycleRegistration.java Bicycle.java

To run the program: 1. javac Bicycle.java (compile)


2. javac BicycleRegistration.java (compile)
3. java BicycleRegistration (run)
Class Diagram for Bicycle

Bicycle

- ownerName
Method Listing
We list the name and the
data type of an argument
passed to the method.
Bicycle( )
getOwnerName( )
setOwnerName(String)
Template for Class Definition
Import Statements

Class Comment

class { Class Name

Data Members

Methods
(incl. Constructor)

}
Data Member Declaration
<modifiers> <data type> <name> ;

Modifiers Data Type Name

private String ownerName ;

Note: There’s only one modifier in this


example.
Declaring Member Variables
There are several kinds of
class Bicycle {
variables:
private String ownerName; // Data Member or Fields
• Member variables in a class
private Static int speed = 20; // Class Variable —these are called
fields/data member (non-
public int speedUp() { static fields).
int newSpeed; // Local Variable
int speedIncrement = 4; // Local Variable • Fields declare with Static
newSpeed = speed + speedIncrement modifier, variables that are
return newSpeed;
} common to all objects -
// name is parameter static fields/class variables
public void setOwnerName(String name) { • Variables in a method or
ownerName = name; block of code—these are
}
} called local variables.
• Variables in method
declarations—these are
called parameters.
Constant Variable
We can change the value of a variable. If we want the value to
remain the same, we use a constant.

final double PI = 3.14159;


final int MONTH_IN_YEAR = 12;
final short FARADAY_CONSTANT = 23060;

The reserved word These are constants,


These are called
final is used to also called named
literal constant.
declare constants. constant.

Note. Changing a value of a const is not possible.


E.g. assignment PI = 3.0 will cause an Error;
Exercise: Identify the class data members,
parameters and local variables
class MusicCD {

private String artist;


private String title;
private String id;

public MusicCD(String name1, String name2) {

String ident;

artist = name1;

title = name2;

ident = artist.substring(0,2) + "-" +

title.substring(0,9);

id = ident;
}
...
}
©The McGraw-Hill Companies, Inc. Permission
required for reproduction or display. 4th Ed Chapter 4 - 15
Data Members Should Be private

• Data members are the implementation details of the


class, so they should be invisible to the clients. Declare
them private .
If you wrote down important information such as your bank
account number, student registration ID, and so forth, on a
single sheet of paper. Will this sheet be declared private, and
kept in your desk drawer, or public, and placed next to the
dorm’s public telephone?
Guideline for Visibility Modifiers
• Guidelines in determining the visibility of methods:
• Declare the class methods public if they are used by the other
classes.
• Declare the class methods private if they are used only by the
other methods in the same class.
• Declare the class constants public if you want to make their values
directly readable by the other classes. If the class constants are
used for internal purposes only, then declare them private.
Method Declaration
<modifier> <return type> <method name> ( <parameters> ){
<statements>
}

Modifier Return Type Method Name Parameter

public void setOwnerName ( String name ) {


ownerName = name;
Statements
}
Calling Methods of the Same Class
• It is possible to call method of a class from another
method of the same class.
• in this case, we simply refer to a method without dot notation
Changing Any Class to a Main Class
• Any class can be set to be a main class.
• All you have to do is to include the main method.
class Bicycle {

//definition of the class as shown before comes here

//The main method that shows a sample


//use of the Bicycle class
public static void main(String[] args) {

Bicycle myBike;

myBike = new Bicycle( );


myBike.setOwnerName("Jon Java");

System.out.println(myBike.getOwnerName() + "owns a bicycle");


}
}
Constructor – Special Method
• A constructor is a special method used to create a new instance of the class.

public <class name> ( <parameters> )


{
<statements>
}
Modifier Class Name Parameter

public Bicycle ( ) {
ownerName = “Unassigned”;
}
Statements
Constructors, cont..
A constructors is a special method that have the following features:

1. Same name as the class itself.


2. Do not have a return type (not even void).
3. Constructors play the role to initialize the default value
for all objects data members.
4. Invoked using the new operator when an object is created.
5. Best practice: initialize all the object data members’ value
using constructor.
Types of Constructors
• There are three types of constructors: Default, No-arg constructor and
Parameterized.

<< Constructor >>

Default User-Define

No-arg Parameterized
Types of Constructors - Default
• Constructor that is automatically generated by the compiler if no
constructors have been defined for the class.
• Default constructor provides the default values to the object like 0,
null etc. depending on the data type.
class Bicycle { class Bicycle {
private String ownerName; private String ownerName;
public String getOwnerName( ){ public Bicycle( ){}
return ownerName;
} public String getOwnerName( ){
return ownerName;
public void setOwnerName(String name){ }
ownerName = name; public void setOwnerName(String name){
}
} ownerName = name;
}
}
Invoking Default Constructor
class BicycleRegistration {
public static void main(String[] args) {
Bicycle obj = new Bicycle( );
System.out.println(obj.getOwnerName());
//Assigns owner name for bicycle's object
obj.setOwnerName("John Wick"));
System.out.println(obj.getOwnerName());

}
}

Output:

null
John Wick
Types of Constructors – No Arguments
• A constructor that has no parameters is known as no-arguments
constructor.
class Bicycle {
private String ownerName;
public Bicycle(){
ownerName = "John Wick";
}
public String getOwnerName( ){
return ownerName;
}
public void setOwnerName(String name){
ownerName = name;
}
}
Invoking No Arguments Constructor
class BicycleRegistration {
public static void main(String[] args) {
Bicycle obj = new Bicycle( );
System.out.println(obj.getOwnerName());

}
}

Output:

John Wick
Types of Constructors - Parameterized
• A constructor that has parameters is known as parameterized
constructor – used to initialize fields of the object to certain values.
class Bicycle {
private String ownerName;
public Bicycle(String ownerName){
this.ownerName = ownerName;
}
public String getOwnerName( ){
return ownerName;
}
public void setOwnerName(String name){
ownerName = name;
}
}
Invoking Parameterized Constructor
class BicycleRegistration {
public static void main(String[] args) {
Bicycle obj = new Bicycle("John Wick");
System.out.println(obj.getOwnerName());

}
}

Output:
John Wick
Reserved Word this
• The reserved word this is called a self-referencing pointer
because it refers to an object from the object's method.

: Object

this
Using this to Refer to Data Members
• this can be used to refer to a data member.

class Person { class Person {

int age; int age;

public void setAge(int val) { public void setAge(int age) {


age = val; this.age = age;
} }
. . . . . .
} }
Constructors and this
To call a constructor public Fraction( ) {
//creates 0/1
from another this(0, 1);
}
constructor of the
same class, we may public Fraction(int number) {
//creates number/1
use the reserved this(number, 1);
word this. }

public Fraction(Fraction frac) {


//copy constructor
this(frac.getNumerator(),
frac.getDenominator());
}

public Fraction(int num, int denom) {


setNumerator(num);
setDenominator(denom);
}
The Use of this in the add Method

public Fraction add(Fraction frac) {

int n1, n2, d1, d2;


Fraction sum;

n1 = this.getNumerator(); // get the receiving - this


d2 = this.getDenominator(); // object's num and denom

n2 = frac.getNumerator(); // get frac's num


d2 = frac.getDenominator(); // and denom

sum = new Fraction(n1*d2 + n2*d1, d1*d2);

return sum;
}
The Calling Class

Fraction f1,f2,f3;

f1 = new Fraction(1,2);
f2 = new Fraction(3,4);

f3 = f1.add(f2);

System.out.println(“Sum of ” + f1.toString() + “and” +


f2.toString() + “is” +
f3.toString());

public String toString() {

return getNumerator() + “/” + getDenominator();


}
f1.add(f2)

Because f1 is the
receiving object
(we're calling f1's
method), so the
reserved word this is
referring to f1.
f2.add(f1)

This time, we're


calling f2's method,
so the reserved
word this is
referring to f2.
Arguments and Parameters
• An argument is a value we pass to a method.
• A parameter is a placeholder in the called method to hold the value of
the passed argument.

class Sample {
class Account { parameter
public static void . . .
main(String[] arg) {
Account acct = new Account(); public void add(double amt) {
. . . balance = balance + amt;
acct.add(400); }
. . .
} . . .
}
. . . argument
}
Matching Arguments and Parameters
• The number of arguments and
the parameters must be the
same.
• The matched pair must be
assignment-compatible (e.g.
you cannot pass a double
argument to an int parameter)
• Arguments and parameters are
paired from left to right .
Passing Objects to a Method
• As we can pass int and double values, we can also pass an object to a
method.
• When we pass an object, we are actually pass the reference (address)
of an object
• it means a duplicate of an object is NOT created in the called method
Passing a Student Object
Sharing an Object

• We pass the same Student


object to card1 and card2

• Since we are actually passing a


reference to the same object, it
results in the owner of two
LibraryCard objects pointing to
the same Student object
Returning an Object from a Method
• As we can return a primitive data value from a method, we can return
an object from a method also.
• We return an object from a method, we are actually returning a
reference (or an address) of an object.
• This means we are not returning a copy of an object, but only the reference
of this object
Sample Object-Returning Method
• Here's a sample method that returns an object:
Return type indicates
the class of an object
we're returning from
public Fraction simplify( ) { the method.
Fraction simp;
int num = getNumberator();
int denom = getDenominator();
int gcd = gcd(num, denom);
simp = new Fraction(num/gcd, denom/gcd);
return simp;
} Return an instance of
the Fraction class
A Sample Call to simplify
A Sample Call to simplify (cont'd)
Set & Get Methods
• When implementing a method of a class, use the class’s set and get
methods to access the class’s private data members. This
simplifies code maintenance and reduces the likelihood of errors.
• Also known as setter and getter method.
• Getters and setters encapsulate the data members of a class by
making them accessible only through public methods.
**Encapsulation is the process of hiding information details and
protecting data and behavior of an object from misuse by other objects.
Set & Get Methods
• Set methods
• Known as mutator methods
• Assign/alter the values for private data members

• Get methods
• Known as accessor methods
• Retrieve the values of private data members
• Can control the format of the data it returns
Set & Get Methods Example
Overloaded Methods

• What – Overloaded Methods are the methods that


have the same name but different parameters.
Overloaded Methods
• Methods can share the same name as long as
• they have a different number of parameters (Rule 1) or
• their parameters are of different data types (Rule 2)
• Return type must be the same (Rule 3)

public void myMethod(int x, int y) { ... }


public void myMethod(int x) { ... } Rule 1

public void myMethod(double x) { ... }


public void myMethod(int x) { ... } Rule 2
Why Multiple Constructors - Overloaded
• Give the programmer flexibility in creating instances.
• We can pick one of the several constructors that is suitable.
Selection
Syntax for the if Statement
if ( <boolean expression> )

<then block>
else

<else block> Boolean Expression

if ( testScore < 70 )

Then Block JOptionPane.showMessageDialog(null,


"You did not pass" );

else

JOptionPane.showMessageDialog(null,
Else Block "You did pass " );
Relational Operators
< //less than
<= //less than or equal to
== //equal to
!= //not equal to
> //greater than
>= //greater than or equal to

testScore < 80
testScore * 2 >= 350
30 < w / (h * h)
x + y != 2 * (a + b)
2 * Math.PI * radius <= 359.99
Compound Statements
• Use braces if the <then> or <else> block has multiple statements.

if (testScore < 70)


{
JOptionPane.showMessageDialog(null,
"You did not pass“ ); Then Block
JOptionPane.showMessageDialog(null,
“Try harder next time“ );
}
else
{
JOptionPane.showMessageDialog(null,
“You did pass“ ); Else Block
JOptionPane.showMessageDialog(null,
“Keep up the good work“ );
}
Style Guide
if ( <boolean expression> ) {

}
else { Style 1

}

if ( <boolean expression> )
{

} Style 2
else
{

}
The if-then Statement

if ( <boolean expression> )

<then block>

Boolean Expression

if ( testScore >= 95 )

JOptionPane.showMessageDialog(null,
Then Block "You are an honor student");
if – else if Control
if (score >= 90)
System.out.print("Your grade is A");

Test Score Grade else if (score >= 80)


90  score A System.out.print("Your grade is B");
80  score  90 B
else if (score >= 70)
70  score  80 C
System.out.print("Your grade is C");
60  score  70 D
score  60 F else if (score >= 60)
System.out.print("Your grade is D");

else
System.out.print("Your grade is F");
The Nested-if Statement
• The then and else block of an if statement can contain
any valid statements, including other if statements. An if
statement containing another if statement is called a
nested-if statement.

if (testScore >= 70) {


if (studentAge < 10) {
System.out.println("You did a great job");
} else {
System.out.println("You did pass"); //test score >=
70
} //and age >= 10
} else { //test score < 70
System.out.println("You did not pass");
}
Boolean Operators
• A boolean operator takes boolean values as its operands
and returns a boolean value.
• The three boolean operators are
• and: &&
• or: ||
• not !

if (temperature >= 65 && distanceToDestination < 2) {


System.out.println("Let's walk");
} else {
System.out.println("Let's drive");
}
Semantics of Boolean Operators
• Boolean operators and their meanings:

P Q P && Q P || Q !P
false false false false true

false true false true true

true false false true false

true true true true false


Operator Precedence Rules
Comparing Objects
• With primitive data types, we have only one way to
compare them, but with objects (reference data type),
we have two ways to compare them.
1. We can test whether two variables point to the same object
(use ==), or
2. We can test whether two distinct objects have the same
contents (use .equals() method).
Using == With Objects (Sample 1)
String str1 = new String("Java");
String str2 = new String("Java");

if (str1 == str2) {
System.out.println("They are equal");
} else {
System.out.println("They are not equal");
}

Not equal because str1 and


They are not equal str2 point to different
String objects.
Using == With Objects (Sample 2)
String str1 = new String("Java");
String str2 = str1;

if (str1 == str2) {
System.out.println("They are equal");
} else {
System.out.println("They are not equal");
}

They are equal It's equal here because


str1 and str2 point to the
same object.
Using equals with String
String str1 = new String("Java");
String str2 = new String("Java");

if (str1.equals(str2)) {
System.out.println("They are equal");
} else {
System.out.println("They are not equal");
}

They are equal It's equal here because str1 and str2
have the same sequence of
characters.
The Semantics of ==
In Creating String Objects
The switch Statement
int gradeLevel;
gradeLevel = JOptionPane.showInputDialog("Grade (Frosh-1,Soph-2,...):" );

switch (gradeLevel) {
This statement
case 1: System.out.print("Go to the Gymnasium"); is executed if
break; the gradeLevel
is equal to 1.
case 2: System.out.print("Go to the Science Auditorium");
break;

case 3: System.out.print("Go to Harris Hall Rm A3");


break;

case 4: System.out.print("Go to Bolt Hall Rm 101"); This statement


is executed if
break;
the gradeLevel
} is equal to 4.
Syntax for the switch Statement
switch ( <arithmetic expression> ) {
<case label 1> : <case body 1>

<case label n> : <case body n>
}
Arithmetic Expression
switch ( gradeLevel ) {
case 1: System.out.print("Go to the Gymnasium");
break;
Case
case 2: System.out.print("Go to the Science Auditorium");
Label
break;
case 3: System.out.print("Go to Harris Hall Rm A3"); Case
break; Body
case 4: System.out.print("Go to Bolt Hall Rm 101");
break;
}
Repetition
Syntax for the while Statement
while ( <boolean expression> )

<statement>

Boolean Expression

while ( number <= 100 ) {

sum = sum + number;


Statement
(loop body)
number = number + 1;
}
Syntax for the do-while Statement
do
<statement>

while ( <boolean expression> ) ;

do {

sum += number; Statement


number++; (loop body)

} while ( sum <=


1000000 );

Boolean Expression
Syntax for the for Statement
for ( <initialization>; <boolean expression>; <increment> )

<statement>

Boolean
Initialization Increment
Expression

for ( i = 0 ; i < 20 ; i++ ) {

number = scanner.nextInt(); Statement


sum += number; (loop body)
}
The Nested-for Statement
• Nesting a for statement inside another for statement is
commonly used technique in programming.
• Let’s generate the following table using nested-for
statement.
Generating the Table
int price;
for (int width = 11; width <=20, width++){

for (int length = 5, length <=25, length+=5){

price = width * length * 19; //$19 per sq. ft.


INNER
OUTER

System.out.print (“ “ + price);
}
//finished one row; move on to next row
System.out.println(“”);
}
Common Programming Error
• Declaring more than one public class in the same file is a
compilation error.
• A compilation error occurs if the number of arguments in a method
call does not match the number of parameters in the method
declaration.
• A compilation error occurs if the types of the arguments in a method
call are not consistent with the types of the corresponding
parameters in the method declaration.

You might also like