IT 114: Introduction to Java
Class 27
Topics
Review
New Material
Homework 9
Homework 9 is due this Sunday at 11:59 PM.
You will find the assignment here.
If you have a problem or a question, make a post on the Class Discussion Area.
Review
Writing Better Programs
- In the early days of programming the organization of code was left to individual programmers
- The programs did not have much structure and were hard to read
- Researches in software engineering began to think of better approaches
- One technique was to break up a big program into a individual methods
- Functions are what Java calls methods
- This is sometimes called
procedural programming
- This made programs easier to read
- It also made the programs easier to debug
- Because all the code that did a particular thing was is one place
- The first part of debugging is finding where the error occurs
- Well designed functions or methods make the program easier to narrow the search for the problem
Object Oriented Programming
- The key idea behind object oriented programming is that certain variables naturally go together
- And certain methods are needed to operate on these variables
- To create an
object
you need to define a
class
- A class is a template that Java uses to create individual objects
- The objects are the things in memory
- But the class is the blueprint used to create individual objects
- The class defines all variable and methods inside the object
- Every class must have a special method which is used to create an object of the class
- This special method is called a
constructor
- The object of a given class created by the constructor is called an
instance
Objects and Values
- A variable
can only hold one value
- But objects can hold many values
- Putting all the variables describing one thing in a
single class makes it easier to work with these values
Classes and Objects
- There are two types of classes
- A static class cannot create objects
- There are two ways to use a static class
- The static class Math is an example of the first kind of static class
- Most Java classes are not static
- They are templates used to create objects
- Each class of this type has
- Variables to hold values
- Methods that work with those values
- Special methods to create an object of the class
- Real world Java programs have many classes
Point Objects
Defining a Class
Fields
- Fields
hold an object's values
- You can think of them as variables inside the object
- Fields are declared outside the object's methods
- That means they can be used by any of the methods in an object
- You declare a field the same way you declare a
local variable
inside a method
DATA_TYPE FIELD_NAME;
- Fields are at the top of the class right after the class header
New Material
The Implicit Parameter
- The code for an
instance method
knows about the fields in the object in which it lives
- So when you call such a method not have to specify the object in which the values are located
- The object is an
implicit parameter
of the instance method
- That means a method does not need a parameter to access the object's fields
- Our latest version of our Point class looks like this
public class Point2{
int x;
int y;
public void translate(int dx, int dy) {
x += dx;
y += dy;
}
}
- Each method in a Point2 object
has access to all field of that class
- It also has access to all the other instance methods
- After Point2Driver executes the following statements
Point2 p = new Point2();
p.x = 7;
p.y = 2;
- Here's what the situation in memory looks like
- When Point2Driver executes
p.translate(-2, 3);;
- dx in translate gets the value -2
and dy gets the value 3
- So the situation in memory looks like this
Mutators and Accessors
- The translate method changes the values contained in
the object
- Methods that change one or more fields are called
mutators
- By convention, the names of mutators often begin with the word "set"
- For example setID or setTitle
- For this reason, mutators are often called
setters
- The return type of a mutator is usually void
- Mutators normally take parameters which are either the new values for the fields
- Or values which are used to modify the current value of the fields
- A second important category of instance methods are
accessors
- Accessors return the value of a field without changing that value
- The names of accessors sometimes begin with the word "get"
- For example getBalance
- Accessors are sometimes called
getters
- If the accessor returns a boolean value the name often begins with "is" ...
- For example isEmtpy
Accessors for Point
- The simplest kind of accessor just returns the value of a field
- We can add getters for each field in our Point class
public int get_x(){
return x;
}
public int get_y(){
return y;
}
- Now we create a driver to test it
public class Point3Driver{
public static void main(String[] args) {
Point3 p = new Point3();
p.x = 7;
p.y = 2;
System.out.println("p is (" + p.get_x() + ", " + p.get_y() + ")");
}
}
$ java Point3Driver
p is (7, 2)
- Why bother to do this when the driver could simply write
System.out.println("p is (" + p.x + ", " + p.y + ")");
- As we will discuss later, it is dangerous to leave fields unprotected
- So that any code the uses the class can change the field values
- Soon I will show you how you can prevent this
- But when we do we will need to provide accessors for the fields
Another Point Accessor
- Point objects have a position on the x y plane
- So we might want to know this distance of the point from the origin
- The origin is the point with coordinates (0,0)
- Let's draw a line connecting two points on the x y plane
- Now let draw a line from showing the difference in
the x position of the two points
- And another one showing the difference in the y positions
- This gives us a right triangle
- With the hypotenuse representing the difference between the two points
- This means we can use the Pythagorean theorem to calculate the distance
- The theorem says
The square of the hypotenuse equals the sum of the squares of the other two sides.
- One side is the difference in the y position of the two points
- The other is the difference in the x position
- So we can write the formula
hypotenuse * hypotenuse = difference_x * difference_x + difference_y * difference_y
- Or
hypotenuse = square_root (difference_x * difference_x + difference_y * difference_y)
- We want the distance from the origin, which has the coordinates (0, 0)
- The means the difference in the x position is simply the x coordinate of p2
- And the difference in the y position is the y coordinate of p2
- So the Java expression below will calculate the distance
Math.sqrt(x * x + y * y);
- Here is the method code
public double distance_from_origin() {
return Math.sqrt(x * x + y * y);
}
- Notice the return type is
double
- We can test this with the following driver
public class Point4Driver{
public static void main(String[] args) {
Point4 p = new Point4();
p.x = 7;
p.y = 2;
System.out.println("p is (" + p.get_x() + ", " + p.get_y() + ")");
System.out.println("p is " + p.distance_from_origin());
}
}
$ java Point4Driver.java
p is (7, 2)
p is 7.280109889280518
- This method is still an accessor even though it does not directly give us the values of the field
Another Mutator Method
- We already have one mutator method, translate
- This method move a point from one position to another
- It's parameters are the change in the x and y position
- But if we simply want to give the point new x
an y we need a new mutator method
- The code for this method simply changes the x
and y field values
public void set_location(int new_x, int new_y){
x = new_x;
y = new_y;
}
- Notice that I could not call the parameters x
and y
- If I did, the code would read
x = new_x;
y = new_y;
- A new driver shows the new method works
public class Point5Driver{
public static void main(String[] args) {
Point5 p = new Point5();
p.x = 7;
p.y = 2;
System.out.println("p is (" + p.get_x() + ", " + p.get_y() + ")");
p.set_location(5,4);
System.out.println("p is (" + p.get_x() + ", " + p.get_y() + ")");
}
}
$ java Point5Driver
p is (7, 2)
p is (5, 4)
Classes for Other Programs To Use
- Classes such as Point are used to create objects
- A class that creates objects never a program that does something useful
- Instead it is used by static, driver classes to do their work
- These static classes are sometimes called client programs
- If you look at the classes that come with Java you will
sometimes find many methods
- And some of these methods look so similar that you wonder
why they were created
- The people who design these classes know that
the class will be used by many different programmers
- And individual programmers may approach their task in different ways
- So the designers tend to create many different methods
in the hope that each programmer will find the method they need
Finding the Distance Between Two Points
- Let's create a method that will determine the distance between two
point objects
- This method will have to take as its only parameter another
Point object
- Again we will use the formula from thePythagorean theorem
hypotenuse = square_root (difference_x * difference_x + difference_y * difference_y)
- Here is the code
public double distance(Point6 p){
int x_diff = x - p.get_x();
int y_diff = y - p.get_y();
return Math.sqrt(x_diff * x_diff + y_diff * y_diff);
}
- The trick her is calculating the difference in position
- distance is an instance method so it
knows the value of the x and y
fields of its own object
- But it needs to the get_x and get_y
methods of its parameter p
- But we could have written this instead
int x_diff = p.get_x() - x;
int y_diff = p.get_y() - y;
- Doesn't the order matter?
- No because that will only change the sign of the result
- And we square these values to they will always be positive
- Here is the driver
public class Point6Driver{
public static void main(String[] args) {
Point6 p1 = new Point6();
p1.x = 1;
p1.y = 2;
Point6 p2 = new Point6();
p2.x = 4;
p2.y = 6;
System.out.println("p is (" + p1.get_x() + ", " + p1.get_y() + ")");
System.out.println("p is (" + p2.get_x() + ", " + p2.get_y() + ")");
System.out.println("The distance between p1 and p2 is " + p1.distance(p2));
}
}
$ java Point6Driver
p is (1, 2)
p is (4, 6)
The distance between p1 and p2 is 5.0
A New Version of distance_from_origin
- If you look at the two methods at the two methods distance
and distance_from_origin they look very similar
public double distance(Point6 p){
int x_diff = x - p.get_x();
int y_diff = y - p.get_y();
return Math.sqrt(x_diff * x_diff + y_diff * y_diff);
}
public double distance_from_origin() {
return Math.sqrt(x * x + y * y);
}
- This violates the DRY principle
- Don't Repeat Yourself
- If you think of it, distance_from_origin
is just a special case of distance
- Where one point is the origin (0,0)
- So we can rewrite distance_from_origin
like this
public double distance_from_origin() {
Point7 p = new Point7();
p.set_location(0, 0);
return distance(p);
}
- Running the driver shows they are equivalent
public class Point7Driver{
public static void main(String[] args) {
Point7 p1 = new Point7();
p1.x = 4;
p1.y = 6;
Point7 p2 = new Point7();
p2.x = 0;
p2.y = 0;
System.out.println("p1 is (" + p1.get_x() + ", " + p1.get_y() + ")");
System.out.println("p2 is (" + p2.get_x() + ", " + p2.get_y() + ")");
System.out.println("The distance between p1 and p2 is " + p1.distance(p2));
System.out.println("The distance of p1 from the origin is " + p1.distance_from_origin());
}
}
[
$ java Point7Driver
p1 is (4, 6)
p2 is (0, 0)
The distance between p1 and p2 is 7.211102550927978
The distance of p1 from the origin is 7.211102550927978
Refactoring
- What we did above is an example of
refactoring
- Refactoring is where you take some code the already works properly
- And make a series of small changes to make it better
- The secret is that the changes are small
- So you can test after every small change
- And fix any problems you find
- The most important feature of any program is that it works
- So you should not waste time when writing it to make it easy to read
- Or more efficient
- Once you have working code you can refactor it to make it better
- As time permits
Telling Whether Two Point Objects Are the Same
- It would be useful to know whether two point are the same
- They are if they have the same x and y coordinates
- Here is the code for an equals method
public boolean equals(Point8 p){
return x == p.get_x() && y == p.get_y();
}
-
public class Point8Driver{
public static void main(String[] args) {
Point8 p1 = new Point8();
p1.x = 5;
p1.y = 4;
Point8 p2 = new Point8();
p2.x = 5;
p2.y = 4;
Point8 p3 = new Point8();
p3.x = 8;
p3.y = 10;
System.out.println("p1 is (" + p1.get_x() + ", " + p1.get_y() + ")");
System.out.println("p2 is (" + p2.get_x() + ", " + p2.get_y() + ")");
System.out.println("p1 and p2 " + p1.equals(p2));
System.out.println("p3 is (" + p3.get_x() + ", " + p3.get_y() + ")");
System.out.println("p1 and p3 " + p1.equals(p3));
}
}
$ java Point8Driver
p1 is (5, 4)
p2 is (5, 4)
p1 and p2 true
p3 is (8, 10)
p1 and p3 false
Do No Harm
- The second ACM general ethical principle is
Avoid harm
- As examples of harm the ACM gives
- Unjustified physical or mental injury
- Unjustified destruction or disclosure of information
- Unjustified damage to property, reputation, and the environment
- Social networks have been used to bully and harass people, especially women and minorities
- IT skills have been used for these purposes
- They have also been used to invade people's privacy and reveal personal information
- Even seemingly neutral activities can have bad consequences
- Bitcoin mining uses as much power as a small country according to
some estimates
Class Quiz
Attendance
Class Exercise