Design
Circle
centre
radius
circumference()
area()
Classes
• The basic syntax for a class definition:
}
• The fields (data) are also called the instance variables
Adding Methods
• A class with only data fields has no life. Objects
created by such a class cannot respond to any
messages.
• Methods are declared inside the body of the class
but immediately after the declaration of data fields.
• The general form of a method declaration is:
type MethodName (parameter-list)
{
Method-body;
}
Adding Methods to Class Circle
– This means
width = width + 10
Answer:
double unitPrice = 1.95;
int quantity = 2;
Self Check 2.3
• Use the variables declared in Self Check 2.2 to display the
total purchase price.
Answer:
System.out.print("Total price: ");
System.out.println(unitPrice * quantity);
Self Check 2.4
• What are the types of the values 0 and "0"?
Answer: double
Self Check 2.6
• Which of the following are legal identifiers?
Greeting1
g
void
101dalmatians
Hello, World
<greeting>
Answer:
String myName = "John Q. Public";
Self Check 2.8
• Is 12 = 12 a valid expression in the Java language?
• Example: toUpperCase
String river = “Mississippi”;
String bigRiver = river.toUpperCase();
The Public Interface of a Class
The controls of a car form its public
interface. The private implementation
is under the hood.
• Example:
public int length()
– There are no arguments
– The return value has the type int
Method Declaration - continued
• Example:
public String replace(String target, String replacement)
– Has two arguments, target and replacement
– Both arguments have type String
– The returned value is another string
• Example:
public void println(String output)
– Has an argument of type String
– No return value
– Uses the keyword void
Method Declaration - continued
• A class can declare two methods with the same name and
different argument types.
• The PrintStream class declares another println method
public void println(int output)
– Used to print an integer value
Answer: river.length() or
"Mississippi".length()
References
• Instructor materials associated to “Big Java: Early Objects”. By Cay Horstmann. Publisher:
Wiley, ISBN 978-1-118-43111-5.