Classesx - Issaquah Connect

Download Report

Transcript Classesx - Issaquah Connect

Unit 6 - Classes
WHAT
Classes
• Classes allow us to encapsulate behavior and state that could
be useful for the future
• We have been using classes for some time now:
• Scanner, String, ArrayList
• We have already seen an example of how classes can be
useful
• Our FractionCalculator project
• Wouldn’t you have liked to have returned an object that
contained both the numerator and denominator instead of
using class fields/variables?
• We have actually been declaring classes all along!
• public class MyClass { ... }
Class Definition
• Classes are defined using the class keyword:
public class <class-name> {
<methods>
<variables>
}
• Note that static is missing. From here on out, static classes will
be used for client code.
• Remember our rules/conventions:
• Class names are like variable names:
• Letters, digits, underscores only
• Start with letter
• Class names begin with a capital letter
• Use another capital letter for each new word
• e.g. Date, MixedFraction, TicTacToeBoard
Class Definition
• Classes consist of three components:
• [Functionality]Methods
• Provide class behavior
• Defined just like we have been, except don’t use static
• [Data] Variables
• Store class state
• Declared like we’re used to, but usually prefix with private
• Scope is the entire class
• [Functionality] Constructors
• Define how to create instances of the class
• Really a special case of methods
WHY
Why
• Some programming problems are best thought of as a
collection of objects that interact with each other.
A programming problem
• Given a file of cities' (x, y) coordinates,
which begins with the number of cities:
6
50 20
90 60
10 72
74 98
5 136
150 91
• Write a program to draw the coordinates for cities, then display
whether your car can make a given city by turning all cities red that
are within a given radius:
Current location x? 100
Current location y? 100
Driving range? 75
A bad solution
Scanner input
int cityCount
int[] xCoords
int[] yCoords
=
=
=
=
new Scanner(new File("cities.txt"));
input.nextInt();
new int[cityCount];
new int[cityCount];
for (int i = 0; i < cityCount; i++) {
xCoords[i] = input.nextInt(); // read each city
yCoords[i] = input.nextInt();
}
...
• parallel arrays: 2+ arrays with related data at same indexes.
• Considered poor style.
Observations
• The data in this problem is a set of points.
• It would be better stored as Point objects.
• A Point would store a city's x/y data.
• We could compare distances between Points
to see whether a car can reach a given city.
• Each Point would know how to draw itself.
• The overall program would be shorter and cleaner.
Classes and objects
• class: A program entity that represents either:
1. A program / module, or
2. A template for a new type of objects.
• The DrawingPanel class is a template for creating
DrawingPanel objects.
• object: An entity that combines state and behavior.
• object-oriented programming (OOP): Programs that perform
their behavior as interactions between objects.
Blueprint analogy
iPod blueprint
state:
current song
volume
battery life
behavior:
power on/off
change station/song
change volume
choose random song
creates
iPod #1
iPod #2
iPod #3
state:
song = "1,000,000 Miles"
volume = 17
battery life = 2.5 hrs
state:
song = "Letting You"
volume = 9
battery life = 3.41 hrs
state:
song = "Discipline"
volume = 24
battery life = 1.7 hrs
behavior:
power on/off
change station/song
change volume
choose random song
behavior:
power on/off
change station/song
change volume
choose random song
behavior:
power on/off
change station/song
change volume
choose random song
Clients of objects
• client program: A program that uses objects.
• Example: DrivingRange is a client of DrawingPanel and
Graphics.
DrawingPanel.java (class)
DrivingRange.java (client program)
public class DrivingRange {
main(String[] args) {
new DrawingPanel(...)
new DrawingPanel(...)
...
}
}
public class DrawingPanel {
...
}
Classes Summary
• What are the 3 components of a class?
• Methods
• Fields
• Constructors
• What is difference between a class and an object?
• A class is a blueprint for how to create an instance of an object.
OBJECT STATE: FIELDS
Point class, version 1
public class Point {
private int x;
private int y;
}
• The above code creates a new type named Point.
• Each Point object contains two pieces of data:
• an int named x, and
• an int named y.
• Point objects do not contain any behavior (yet).
As a class: Create a class named Point
Fields
• field: A variable inside an object that is part of its state.
• Each object has its own copy of each field.
• Declaration syntax:
type name;
• Example:
public class Student {
private String name; // each Student object has
private double gpa; // a name and gpa field
}
Accessing fields
• Other classes can access/modify an object's fields.
• access:
• modify:
variable.field
variable.field = value;
• Public fields tend to link you to a particular implementation and limit
your flexibility in changing your code.
• Example:
Point p1 = new Point();
Point p2 = new Point();
System.out.println("the x-coord is " + p1.x);
p2.y = 13;
// access
// modify
Access Control
• We’ve been using public in a lot of places
• public is a Java access specifier
• Others are private and protected
• Access specifiers tell Java who should be able to see and use
the class/method/variable we’re defining
• public: can be seen/used by everyone anywhere
• private: can only be seen/used by the class itself
• Ignore protected for now– we won’t be using it.
Access Control
• Now that we’re defining classes, we’ll start using private
for some things
• Like with variable names, there are no rules about this, just
conventions
• We’ll use the following conventions:
• Almost all fields will be private
• Almost all constructors will be public
• Methods will be public if other classes will want to use them,
and private otherwise
• If you’re not sure, feel free to ask
Methods
•
instance method (or object method): Exists inside each object of a class and gives behavior to each
object.
public type name(parameters) {
statements;
}
•
same syntax as static methods, but without static keyword
Example:
public void shout() {
System.out.println("HELLO THERE!");
}
• accessor:
•
•
Examples: distance, distanceFromOrigin
often has a non-void return type
• mutator:
•
A method that lets clients examine object state.
A method that modifies an object's state.
Examples: setLocation, translate
Accessor Methods
• Because we declare our variables as private, others cannot
access them
Movie megamind = new Movie(“Megamind”);
System.out.print(megamind.title);
work
// won’t
• Instead, we use accessor methods to provide access to the
data
• This provides a layer of abstraction over our data
• Accessor methods typically names of the form
getVariable and don’t take arguments
Accessor (Getter) Methods
// accessor method
public String getTitle() {
return title;
}
// simple accessor method
public String[] getActors() {
return actors;
}
As a class: Add getX and getY accessor methods
Other Accessor Methods
• We can also provide accessor methods for data for which we
don’t store a variable
• This is another reason we use methods instead of direct variable
access
• These getters are named similarly, but do not have a
corresponding variable
public String getLeadActor() {
// lead actor always stored first in list
return actors[0];
}
Mutator Methods
• Mutator methods are the analog of getter methods
• They are used to set the value of a variable
• Mutator methods typically have names of the form
setVariable, have a void return type, and take a single
argument of the relevant type
• We can also define mutator methods that don’t simply set a
variable, but modify something more complex
Mutator Methods
// simple mutator method
public void setTitle(String title) {
this.title = title;
}
// mutator method
public void addActor(String actor) {
String[] newActors = new String[actors.length + 1];
for (int i = 0; i < actors.length; i++) {
newActors[i] = actors[i];
}
newActors[actors.length] = actor;
actors = newActors;
}
As a class: Add a setLocation mutator method
Other Methods
• We can also provide any other methods we might want or that
might be useful
• These other methods will use our variables, and can possibly
call other methods
public boolean isInFilm(String actor) {
for (int i = 0; i < actors.length; i++) {
if (actors[i].equals(actor)) {
return true;
}
}
return false;
}
Constructors
• Constructors are defined just like other methods, but with no
return type or value
• Constructors can be overloaded, just like other methods
public Movie(String title) {
title = title;
}
public Movie(String title, String[] actors) {
title = title;
actors = actors;
}
• These constructors won’t work– why not?
• Parameters are shadowing the fields
As a class: Add two constructors: one that takes no
parameters and one that takes x and y values.
this keyword
• We can access the current object by using the this keyword
• In a constructor, this is the object being created
• In any other method, this is the target of the method call
public Movie(String title) {
this.title = title;
}
public Movie(String title, String[] actors) {
this.title = title;
this.actors = actors;
}
Exercise
• Exercise: Define a class to represent a high school course. Your class
should include methods to provide the following information about
the course:
•
•
•
•
•
•
•
Course title
Teacher name
Room number
Period
Is a particular student enrolled in the course?
Bonus: Does this course meet at the same time as another course?
Bonus: Does this course have the same teacher as another course?
• Think about what variables, methods, and constructors your class will
need
• Exercise 2: Create a client program that creates multiple instances of
your class and calls the “Is a particular student enrolled in the
course” method and the bonus methods, if you did those.
IMPLICIT PARAMETER, ARRAYS AND
TOSTRING
The toString method
tells Java how to convert an object into a String
Point p1 = new Point(7, 2);
System.out.println("p1: " + p1);
// the above code is really calling the
following:
System.out.println("p1: " + p1.toString());
• Every class has a toString, even if it isn't in your code.
• Default: class's name @ object's memory address (base 16)
Point@9e8c34
toString syntax
public String toString() {
code that returns a String representing this object;
}
• Method name, return, and parameters must match exactly.
• Example:
// Returns a String representing this Point.
public String toString() {
return "(" + x + ", " + y + ")";
}
The implicit parameter
• implicit parameter:
The object on which an instance method is called.
• During the call p1.draw(g);
the object referred to by p1 is the implicit parameter.
• During the call p2.draw(g);
the object referred to by p2 is the implicit parameter.
• The instance method can refer to that object's fields.
• We say that it executes in the context of a particular object.
• draw can refer to the x and y of the object it was called on.
Calling another constructor
public class Point {
private int x;
private int y;
public Point() {
this(0, 0);
constructor
}
// calls (x, y)
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
...
• Avoids redundancy between constructors
• Only a constructor (not a method) can call another constructor
Summary
• What method does print and println call on an object to
be printed?
• toString
• In the following code, what is the implicit parameter?
p1.draw(g)
• p1
• How does a constructor call another constructor?
public Point() {
this(0, 0);
}
Exercise
• Exercise:
• Extend your high school course class by adding a class constructor
to create a course from user input.
• Use multiple constructors, if appropriate and re-use code as much
as possible. i.e. have the constructors call one main one, if
possible.
• Add a toString method that outputs a reasonable reflection of
a course.
• Add code to your client code to print out a course
• Your client code could create an array of courses that represent the
courses that you are taking in this semester. In that case, print out all
of the courses in the array.
• Add a field that represents the students in the class.
• Add a addStudent method.
Exercise
• Exercise:
• Add a field that represents the students in the class.
• Add a addStudent method.
ENCAPSULATION
Abstraction
• abstraction: A distancing between ideas and details.
• We can use objects without knowing how they work.
• abstraction in an iPod:
• You understand its external behavior (buttons, screen).
• You don't understand its inner details, and you don't need to.
Abstraction
• abstraction: A distancing between ideas and details.
• We can use objects without knowing how they work.
• abstraction in a Car
• You understand that you use the steering wheel to turn
• You understand that you press a pedal to go faster or to stop.
• When you press that pedal to go faster you are abstracted away from
how that action is implemented.
• In a gas-powered engine, what happens?
• In an electric car, what happens?
• You don’t have to care. You just need to need to use the interface.
• What happens if a better way to implement the acceleration is
discovered?
• Does the interface need to change?
• No! That’s an implementation detail that is abstracted away from the
client.
Encapsulation
• abstraction: A distancing between ideas and details.
• encapsulation: Hiding implementation details from clients.
• We can use objects without knowing how they work.
• Encapsulation is a way of implementing abstraction.
• separates external view (behavior) from internal view (state)
• protects the integrity of an object's data
Accessing private state
// A "read-only" access to the x field
("accessor")
public int getX() {
return x;
}
// Allows clients to change the x field
("mutator")
public void setX(int newX) {
x = newX;
}
• Client code will look more like this:
System.out.println(p1.getX());
p1.setX(14);
Benefits of encapsulation
• Abstraction between object and clients
• Protects object from unwanted access
• Example: Can't fraudulently increase an Account's balance.
• Can change the class implementation later
• Example: Point could be rewritten in polar
coordinates (r, θ) with the same methods.
• Can constrain objects' state (class invariants)
• Example: Only allow Accounts with non-negative balance.
• Example: Only allow Dates with a month from 1-12.
CONSTANTS
Constants
• Consider the following method we could add to our high
school course class:
public boolean mysteryMethod() {
return (students.length > 30);
}
• What would you call this method?
Constants
• What if the method looked like this?
public boolean mysteryMethod() {
return (students.length > MAX_CLASS_SIZE);
}
• Now what would you call it?
Constants
• The number 30 in the original method is called a magic
number
• A number literal that has no context
• Magic numbers are bad for a couple reasons:
• Poor documentation
• Potential for bugs if value changes
• Especially if the value is used in multiple places
• We avoid magic numbers by defining constants
• A constant is a variable whose value cannot change once it has
been assigned
Constants
•
•
•
•
Are defined using the final keyword
Typically named in ALL_CAPS
Follow normal scope rules for variables
Can be defined at the class or method level
public class HighSchoolCourse {
...
public static final int MAX_CLASS_SIZE = 30;
public boolean isFull() {
return (students.length <= MAX_CLASS_SIZE);
}
}
Constants
• Class constants are typically declared as public and static
• Class constants can be initialized either at the declaration or in
the constructor (but not both)
• Class constants cannot be initialized or assigned anywhere
else
STATIC METHODS/FIELDS
Static members
• static: Part of a class, rather than part of an object.
• Object classes can have static methods and fields.
• Not copied into each object; shared by all objects of that class.
class
state:
private static int staticFieldA
private static String staticFieldB
behavior:
public static void someStaticMethodC()
public static void someStaticMethodD()
object #1
object #2
object #3
state:
int field2
double field2
state:
int field1
double field2
state:
int field1
double field2
behavior:
public void method3()
public int method4()
public void method5()
behavior:
public void method3()
public int method4()
public void method5()
behavior:
public void method3()
public int method4()
public void method5()
Static fields
private static type name;
or,
private static type name = value;
• Example:
private static int theAnswer = 42;
• static field: Stored in the class instead of each object.
• A "shared" global field that all objects can access and modify.
• Like a class constant, except that its value can be changed.
Accessing static fields
• From inside the class where the field was declared:
fieldName
fieldName = value;
// get the value
// set the value
• From another class (if the field is public):
ClassName.fieldName
ClassName.fieldName = value;
// get the value
// set the value
• generally static fields are not public unless they are final
Math.PI
Static methods
// the same syntax you've already used for methods
public static type name(parameters) {
statements;
}
• static method: Stored in a class, not in an object.
• Shared by all objects of the class, not replicated.
• Does not have any implicit parameter, this;
therefore, cannot access any particular object's fields.
Static Method example
public class BankAccount {
// static count of how many accounts are created
// (only one count shared for the whole class)
private static int objectCount = 0;
// clients can call this to find out # accounts created
public static int getNumAccounts() {
return objectCount;
}
// fields (replicated for each object)
private String name;
private int id;
}
public BankAccount() {
objectCount++;
// advance the id, and
id = objectCount; // give number to account
}
...
public int getID() {
// return this account's id
return id;
}
Summary
• How is abstraction and encapsulation related?
• Encapsulation is a way of implementing abstraction.
• How do you define a class constant?
public class HighSchoolCourse {
...
public static final int MAX_CLASS_SIZE = 30;
• How does an instance method differs from a static method?
• Static methods are shared by all objects of the class, not
replicated like instance methods are.
• Static methods do not have any implicit parameter, this;
therefore, cannot access any particular object's fields like
instance methods can.
Exercise
• Add a static method that accepts a Scanner object and returns a
Course object by asking the user for input using the Scanner
object.
• Add a field that represents the students in the class.
• Add a MAX_CLASS_SIZE constant to your high school course class.
• Add an isClassFull() method.
• Add an addStudent() that does not allow the student to be added
if the class if full.
• Be sure to give the caller of the method an indication of whether or
not adding the student succeeded. (Printing a message to the
console will not accomplish this.)
ARRAYS OF OBJECTS AND NULL
Two-phase initialization
1) initialize the array itself (each element is initially null)
2) initialize each element of the array to be a new object
// phase 1
Course[] courses = new Course[3];
for (int i = 0; i < courses.length; i++) {
// phase 2
courses[i] = new Course(“CS” + (i +1), “teach”);
}
courses
index
0
1
2
value
Course Object
title = “cs1”
teacher=
“teach”
Course Object
title = “cs2”
teacher=
“teach”
Course Object
title = “cs3”
teacher=
“teach”
Arrays of objects
• null : A value that does not refer to any object.
• The elements of an array of objects are initialized to null.
String[] words = new String[5];
Course[] courses = new Course[3];
index
words
courses
0
1
2
3
4
value null null null null null
index
0
1
2
value null null null
Things you can do w/ null
• store null in a variable or an array element
String s = null;
words[2] = null;
• print a null reference
System.out.println(s);
// null
• ask whether a variable or array element is null
if (words[2] == null) { ...
• pass null as a parameter to a method
System.out.println(null);
// null
• return null from a method (often to indicate failure)
return null;
Null pointer exception
• dereference: To access data or methods of an object with the
dot notation, such as s.length() .
• It is illegal to dereference null (causes an exception).
• null is not any object, so it has no methods or data.
String[] words = new String[5];
System.out.println("word is: " + words[0]);
words[0] = words[0].toUpperCase();
//
ERROR
index 0
1
2
3
4
value null null null null null
Output:
word is: null
Exception in thread "main"
java.lang.NullPointerException
at Example.main(Example.java:8)
Looking before you leap
• You can check for null before calling an object's methods.
String[] words = new String[5];
words[0] = "hello";
words[2] = "goodbye";// words[1],[3],[4] are null
for (int i = 0; i < words.length; i++) {
if (words[i] != null) {
words[i] = words[i].toUpperCase();
}
}
words
index
0
1
2
3
4
value "HELLO" null "GOODBYE" null null
Summary
• What is null?
• A value that does not refer to any object.
Exercise
• Exercise:
• Add a static method that accepts a Scanner object and returns a
Course object by asking the user for input using the Scanner
object.
• Add a field that represents the students in the class.
• Add a MAX_CLASS_SIZE constant to your high school course class.
• Add an isClassFull() method.
• Add an addStudent() that does not allow the student to be added
if the class if full.
• Be sure to give the caller of the method an indication of whether or
not adding the student succeeded. (Printing a message to the
console will not accomplish this.)
1.
Review
Classes vs objects
• Create a class named Ski that has at least 1 constructor, at least 1 method, and at
least one private field
2.
How is abstraction and encapsulation related?
• Create a class named Bobsled that has 1 constructor, 1 accessor method, and 1
private field
3.
How do you define a class constant?
• Create a class named Olympics that has 1 constructor, 1 constant that represents
the maximum # of participants, and 1 method that adds a participant
4.
How does an instance method differs from a static method?
• Create a class named SpeedSkating that has at least one constructor, one instance
method, and one static method.
5.
What method does print and println call on an object to be printed?
• Create a class named Athlete that has at least 1 constructor and a toString method
that returns the details of the athlete.
6.
Implicit parameter and this
• Create a class named CrossCountrySkiing that has two constructors. In one of
the constructors use the this keyword to call the other constructor.
7.
What is null?
• Create a class named Event. In a client program create an array of events, populate
some, but not all of the array elements, and print out the contents of the array. If an
array element is null, output “null”.
Classes and Objects
• What are the 3 components of a class?
• Methods
• Fields
• Constructors
• What is difference between a class and an object?
• A class is a blueprint for how to create an instance of an object.
Abstraction, Constants,
instance methods
• How is abstraction and encapsulation related?
• Encapsulation is a way of implementing abstraction.
• How do you define a class constant?
public class HighSchoolCourse {
...
public static final int MAX_CLASS_SIZE = 30;
• How does an instance method differs from a static method?
• Static methods are shared by all objects of the class, not
replicated like instance methods are.
• Static methods do not have any implicit parameter, this;
therefore, cannot access any particular object's fields like
instance methods can.
toString, implicit parameter
and null
• What method does print and println call on an object to
be printed?
• toString
• In the following code, what is the implicit parameter?
p1.draw(g)
• p1
• What is null?
• A value that does not refer to any object.
• How does a constructor call another constructor?
public Point() {
this(0, 0);
}