Instance Methods

Download Report

Transcript Instance Methods

Java the UML Way
http://www.tisip.no/JavaTheUmlWay/
Constructing Your Own Classes
The Building Block Principle in programming
page 2
Modeling classes
page 3-4
The Surface class
page 5-6
Local variables, parameters, and instance variables
page 7
The Merchandise class
page 8
The contents of a class, details, rules and recommendations page 9 - 15
Some new operators
page 16
Graphics and applets
page 17-18
Subclasses and ”extends”
page 19-21
Ready-made graphics classes
page 22-23
version 2002-04-17
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 4
The Building Block Principle in Programming
• By dividing the problem up into a number of pieces (classes), we can
concentrate on one thing at a time.
• Several people can cooperate on a program. When they are each
working on their own parts, they can work independently from each
other.
• The building blocks can be tested and modified independently. If we
don’t alter the interface for the class, we can change the
implementation as often as we want, without affecting the other
classes.
• If we create the building blocks carefully, we can make some of them
general enough that they can be used later on.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 4, page 2
Modeling Classes
•
The Renovation case from chapter 2
– You just bought an old condominium that you’re going to renovate. You’ve decided
that the bathroom, kitchen, and the electrical installations are fine. However, you
want to replace the flooring in a couple of the rooms and paint and wallpaper some
of them. You need to perform a number of calculations:
• How much paint, or wallpaper, will you need for a wall?
• How many square meters of parquet flooring, or other flooring, will you need for a floor?
• What will the renovation cost for each individual wall, each individual room, and the
entire renovation project?
•
Problems
– Set up a list of objects by looking at the nouns
– Work out a summary of the knowledge that will have to be stored in the system.
These will become attributes to the objects. Set up a list showing the connections
between the attributes and the objects.
– Which calculations have to be done?
– Distribute the responsibility for the calculations between the objects (may be
difficult!)
– Draw a class diagram.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 4, page 3
A Possible Solution
Paint
Wallpaper
Surface
Flooring
name
length
width
name
price
widthOfFlooring
name
price
noOfCoats
noOfSqMPerLiter
name
price
lengthPerRoll
widthPerRoll
getName
getLength
getWidth
getArea
getCircumference
getName
getPricePerM
getWidth
getNoOfMeters
getTotalPrice
getName
getPricePerLiter
getNoOfCoats
getNoOfSqMPerLiter
getNoOfLiters
getTotalPrice
getName
getPricePerRoll
getLengthPerRoll
getWidthPerRoll
getNoOfRolls
getTotalPrice
Every class with its own test program is programmed separately.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 4, page 4
Client Program
Testing
the Surface Class
class FloorCalculations {
public static void main(String[] args) {
/* Step 1: We instantiate an object of the class. */
Surface aFloor = new Surface("Mary's floor", 4.8, 2.3);
Surface
/* Step 2: We retrieve data from the object,
and we let the object perform calculations. */
String name = aFloor.getName();
double width = aFloor.getWidth();
double length = aFloor.getLength();
double area = aFloor.getArea();
double circumference = aFloor.getCircumference();
name
length
width
getName
getLength
getWidth
getArea
getCircumference
}
}
/* Step 3: We present the results on the screen for control. */
System.out.println(
"Information about the floor with the name: " + name + ":");
System.out.println("Width: " + width);
System.out.println("Length: " + length);
System.out.println("Area: " + area);
System.out.println("Circumference: " + circumference);
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 4, page 5
Here is the
Surface Class
class Surface {
private String name;
private double length;
private double width;
instance variables
public Surface(String initName, double
initLength, double initWidth) {
name = initName;
method head
constructor
length = initLength;
Surface
width = initWidth;
public double getCircumference() {
}
name
return 2 * (length + width);
public String getName() {
length
return name;
}
width
}
public double getLength() {
method body
return length;
}
public double getWidth() {
instance
getName
the members of the class =
return width;
methods
getLength
}
variables + methods
getWidth
public double getArea() {
From the client program:
instance methods
return width * length;
getArea
Surface
aFloor
=
new
Surface("Mary's
floor", 4.8, 2.3);
getCircumference }public double getCircumference()
….
{
return 2 * (length + width); double area = aFloor.getArea();
double circumference = aFloor.getCircumference();
}
….
}
System.out.println("Area: " + area);
Solve all the problems, pp. 90-91.
System.out.println("Circumference: " + circumference);
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 4, page 6
Overview
Local variables, parameters and instance variables
•
•
•
•
•
•
•
Local variables are declared in a method and can only be used in the block
where they are declared.
Parameters function as local variables with initial values provided by the
argument list in the method call.
Local variables are not given any definite initial value. That’s up to the
programmer.
Instance variables are declared in a class, but outside all the methods. They can
be used by all the methods in the class.
Instance variables are automatically given initial values according to their data
type. Variables of a number type get the value 0, while boolean variables get
false, and variables of a reference type get the value null.
Problem 1: Change the getCircumference() method such that the sum of the
length and the width is stored in a local variable before the circumference is
calculated and returned.
Problem 2: Set up a list showing all the local variables and all the arguments
in the test client program at slide 5.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 4, page 7
Problem
•
Merchandise
merchandiseName
merchandiseNo
price per kilo witout VAT
get price for an amount without VAT
get price for an amount with VAT
set new price
•
•
Code the Merchandise class
according to the class diagram at
the left. Remember to create a
constructor.
Create a very simple client
program.
Look at your code and show
examples of:
–
–
–
–
–
–
instance variable
instance method
parameter
argument
return statement
statement where an object is
instantiated
Then, solve problem 3 pp. 98-99.
After this practise we'll look at more details on classes.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 4, page 8
Access Modifiers - Private and Public
package access
•
•
•
•
Access modifiers control the
access of classes,
constructors, and members.
private: access only from
inside the class, for example private
from inside all the methods. access
public: access from
everywhere, for example
from a client program.
public
No access modifier =
access
package access, access only
from inside the class' own
package.
class Surface {
private String name;
private double length;
private double width;
public Surface(String initName, double
initLength, double initWidth) {
name = initName;
length = initLength;
width = initWidth;
}
….
If a class' access level is more restrictive than the access level of a constructor or a member,
it's the class' access level that will apply to the constructor/member. If not, it's the access
level of the constructor/member that applies.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 4, page 9
Overloading Names
•
Several methods may have the same name if their signatures are different.
– (A method's signature is the name, and the number and type of the parameters.
The return type and the parameter names are not part of the signature.)
•
Examples from the String class
–
–
–
–
•
int indexOf(int character)
int indexOf(int character, int fromIndex)
int indexOf(String str)
int indexOf(String str, int fromIndex)
Using these methods
String text =
"To day it is January 4th. The daylight in Trondheim is from 09 AM to 15 PM.";
int pos1 = text.indexOf('.'); // pos1 is 24
int pos2 = text.indexOf('4'); // pos2 is 21
int pos3 = text.indexOf('.', pos1 + 1); // pos3 is 74
int pos4 = text.indexOf("is"); // pos4 is 10
int pos5 = text.indexOf("is", pos4 + 1); // pos5 is 52
int pos6 = text.indexOf("is", pos5 + 1); // pos6 is -1 (=not found)
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 4, page 10
Constructors and Initializing Instance Variables
• The constructor name may be overloaded. A class may have several
constructors.
• If we don't create any constructors ourselves, a constructor with empty
parameter list and empty body is made automatically. This is the
default constructor.
• If we create our own constructors, and we want a constructor with
empty parameter list to exist, we have to create that too.
• Variables may be initialized in the declaration:
– private String name = "";
– private double length = 5;
• If these variables get values in the constructor, too, it's the values got in
the constructor that apply.
• A constructor may, but does not have to, assign values to all the
instance variables.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 4, page 11
Constructors in the Surface Class, Examples
public Surface(String initName, double initLength, double initWidth) {
name = initName;
length = initLength;
width = initWidth;
}
public Surface(double initLength) {
length = initLength;
}
public Surface() {
}
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 4, page 12
Instance Methods
•
Examples:
public double getCircumference() { // the return type is a primitive data type
return 2 * (length + width); // returns a value that goes with the return type
}
public String getName() { // the return type is a reference type
return name; // returns the reference to an object
}
public void setWidth(double newWidth) {
width = newWidth;
}
•
Example, using the last method:
aFloor.setWidth(5.3); // Message: ”Hi, you will have a new width of 5.3 meters!”
•
•
•
•
Methods that implement operations that get instance values or calculate results
from these values are called accessors (or get methods). Accessors don’t
change the attributes. getCircumference() and getName() are examples.
Methods that implement operations that change the attribute values are called
mutators (or set methods). setWidth() is an example.
A mutable class is a class that contains mutators.
An immutable class is a class that only contains accessors.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 4, page 13
Hiding Names
• Why doesn't this work?
public void setLength(double length) {
length = length;
}
• The parameter is hiding the instance variable with the same name.
• Parameters and instance variables should have different names.
• Although it is possible for them to have the same names. Then we
separate them by using the keyword this:
public void setLength(double length) {
this.length = length;
}
• this is a reference that always points to the object the Java interpreter is
busy with at any given time.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 4, page 14
Programming Conventions for Classes
•
•
•
•
•
•
•
•
•
These are recommendations, not syntax rules.
Class names start with a capital letter.
Variable names and method names start with lower-case letters.
If the name consists of several words, a capital letter is used for the first letters
of the second word and words that follow it. The underline character and $ are
not used.
Instance variables have the access modifier private.
Constructors have the access modifier public.
Methods have the access modifier public or private.
Class variables and class methods are rarely used.
Accessors and mutators whose jobs are to get or change an attribute have
standardized names:
–
–
–
–
•
public void setNN(type value) // gives a value to the attribute NN
public type getNN() // gets the value for the attribute NN
public void setNN(boolean value)
public boolean isNN()
In addition we have chosen to mark the parameter name in the mutator with
the prefix new. Example:
– public void setLength(double newLength)
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 4, page 15
Some New Operators
• increment operator ++
• decrement operator -• compound assignment operators
value++
value-value += 3
value -= 3
value *= 3
value /= 3
value %= 3
is the same as
is the same as
is the same as
is the same as
is the same as
is the same as
is the same as
value = value + 1
value = value - 1
value = value + 3
value = value - 3
value = value * 3
value = value / 3
value = value % 3
Solve problem 2, page 105.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 4, page 16
Graphics
• The screen being drawn on is divided into pixels, according to the given
resolution, typical 1280 x 1024 points and 1024 x 768 points.
• We decide where the drawing will be by indicating x and y coordinates
relative to the origin in the upper left-hand corner of the window.
(0,0)
x1
x
y1
(x1,y1)
y
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 4, page 17
Applets and Graphics
import java.awt.*; // Graphics and Container classes
import javax.swing.*; // JApplet and JPanel classes
All applets have to be public
subclasses to JApplet (more on
this on next slide).
All applets have an init() method.
The browser instantiates an object of
the SimpleApplet class and sends the
init() message to this object. (Very
different from applications where
we have the main() method.)
Our drawing is described in a
separate class.
The drawing procedure is inside the
paintComponent() method.
public class SimpleApplet extends JApplet {
public void init() {
Container content = getContentPane();
Drawing aDrawing = new Drawing();
content.add(aDrawing);
}
}
class Drawing extends JPanel {
public void paintComponent(Graphics window) {
super.paintComponent(window); // NB!
setBackground(Color.green);
window.drawString("Hello hello", 50, 50);
window.drawOval(40, 30, 100, 40);
}
}
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 4, page 18
Subclasses and ”extends”
• SimpleApplet is a subclass (extends) of JApplet:
– The JApplet class describes (almost) every possible applet.
– The SimpleApplet class describes only applets exactly as ours, with the
green filled circle. These applets make a subset of the former, large set of
applets.
– Everything that is true for the large set of all applets, is also true for our
special applet. The SimpleApplet class inherits all the characteristics of
the JApplet class.
• Drawing is a subclass (extends) of the JPanel class.
• Every Java class is part of the Java class tree.
– The Object class describes what is true for every Java object.
– The other classes are subclasses of this class.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 4, page 19
the superclass
for all other classes
Object
setBackground() and
Component getBackground() are
inherited from here
A segment of the
Java Class Tree
the subclass for
Object and Component
Container
the superclass for
JComponent
JPanel and Drawing
add() is inherited from here
Panel
JPanel
Applet
Drawing
JApplet
getContentPane()
is inherited from here
SimpleApplet
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 4, page 20
The Objects the Different Classes Describe Form Sets
Container
JComponent
JPanel
Drawing
Panel
Applet
JApplet
SimpleApplet
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 4, page 21
The java.awt.Graphics Class
Some methods:
void drawLine(int x1, int y1, int x2, int y2)
void drawOval(int x, int y, int width, int height)
void fillOval(int x, int y, int width, int height)
void drawRect(int x, int y, int width, int height)
void fillRect(int x, int y, int width, int height)
void drawString(String text, int x, int y)
void setFont(Font newFont)
void setColor(Color newColor)
Font getFont()
Color getColor()
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 4, page 22
Classes for Colors and Fonts
The java.awt.Color class
Example:
Color color = Color.gray;
color = color.brighter();
window.setColor(color);
Class Constants:
Color.black Color.blue Color.cyan, ...
Methods:
Color brighter()
Color darker()
The java.awt.Font class
Example:
Font font = new Font("Serif", Font.BOLD, 16);
window.setFont(font);
Constructor:
Font(String name, int style, int size)
Class Constants:
Font.BOLD
Font.ITALIC
Font.PLAIN
Methods:
String getName()
int getSize()
int getStyle()
boolean isBold()
boolean isItalic()
boolean isPlain()
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 4, page 23