Chap 2 Define Ur Own Class
Chap 2 Define Ur Own Class
After you have read and studied this chapter, you should be able to
< or >
Bicycle bike1, bike2;
bike1 = new Bicycle( );
bike2 = new Bicycle( );
The Program Structure and Source
Files
BicycleRegistration 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
Data Members
Methods
(incl. Constructor)
}
Data Member Declaration
<modifiers> <data type> <name> ;
String ident;
artist = name1;
title = name2;
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
Bicycle myBike;
public Bicycle ( ) {
ownerName = “Unassigned”;
}
Statements
Constructors, cont..
A constructors is a special method that have the following features:
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.
return sum;
}
The Calling Class
Fraction f1,f2,f3;
f1 = new Fraction(1,2);
f2 = new Fraction(3,4);
f3 = 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)
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
• 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
<then block>
else
if ( testScore < 70 )
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 ( <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");
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.
P Q P && Q P || Q !P
false false false false true
if (str1 == str2) {
System.out.println("They are equal");
} else {
System.out.println("They are not equal");
}
if (str1 == str2) {
System.out.println("They are equal");
} else {
System.out.println("They are not equal");
}
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;
<statement>
Boolean Expression
do {
Boolean Expression
Syntax for the for Statement
for ( <initialization>; <boolean expression>; <increment> )
<statement>
Boolean
Initialization Increment
Expression
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.