Transcript .ppt

Announcements
• Homework W1 is due today
• Regrades: Ok, but we will regrade the entire
assignment. Must be w/in 72 hours of when
returned
• Consultants start on Sunday. Alan is often in
the lab as well.
CS100
Lecture 4
1
Today’s Topics
• Review
• The Class String
• Printing output: System.out.print,
System.out.println, and System.out.flush()
• Accessing modifiers public and private
• Functions versus procedures, void
• Constructors
CS100
Lecture 4
2
Review
• Classes are conceptually similar to types,
like int, char, double.
• Classes are programmer-defined
• Objects are instances of classes. Objects of
a particular class type get all the fields and
methods associated with that class.
CS100
Lecture 4
3
Review example
Coordinate c1;
Coordinate d1;
c1 = new Coordinate();
d1 = new Coordinate();
c1.setX(3); d1.setX(4); d1.setY(2);
c1.setY(d1.sumSquares());
d1.setY(c1.y);
CS100
Lecture 4
4
Today’s example
// An instance of Employee contains a person's name,
// salary, and year hired. It has a constructor and
// methods for raising the salary, printing the data, and
// retrieving the person's name and the year hired.
public class Employee
{
public String name;
// The person's name
public double pay;
// The person's yearly salary
public int hireDate;
// The year hired
CS100
Lecture 4
5
// Set the name to n
public void setName(String n)
{name= n;}
// Set the salary to s
public void setSalary(double s)
{pay= s;}
// Set the year to y
public void setHireDate(int y)
{hireDate= y;}
// Yield the year the person was hired
public int hireYear()
{return hireDate;}
CS100
Lecture 4
6
// Raise the pay by p percent
public void raiseSalary(double p)
{pay= pay * (1 + p/100.0);}
// Yield the person's name
public String getName()
{return name;}
// Yield a String containing person’s data
public String toString() {
String s= name;
s= s + " " + pay + " " + hireDate;
return s;}
}CS100
Lecture 4
7
Class String
• An instance of class string is a “string” of
characters: abcde, oo145^^!2l, . . .
• Declare as
String d;
• Assigned as:
d = new String(“L. Millett”) // just like other classes
or
d = “L. Millett” // only because strings are common
• Lots of methods available in the String class
CS100
Lecture 4
8
Some String Methods
• charAt(int index) // return char at index
• endsWith(String suffix) // return true if . . .
• toLowerCase() // return string w/no caps
• length() // return length of the string
String str1 = “Strings are cool.”; int n;
if (str1.endsWith(“ool.”))
System.out.println(“Yes”);
n = str1.length();
String str2 = str1.toLowerCase(str1);
CS100
Lecture 4
9
Catenating Strings
• Use the infix operator ‘+’ -- here it means
something different than addition:
• d + “xyz” + “ ” + “qed”
evaluates to
“Lyn Millettxyz qed”
• Note that you need to explicitly put in spaces “ ”
where you want them
CS100
Lecture 4
10
String equality
• Suppose:
// s1
millett
// s2
millett
• if (s1 == s2)
returns false!
• Use if (s1.equals(s2)) instead
• equals is another method of class String
CS100
Lecture 4
11
Printing output
• To print string s in the output window, use
System.out.print(s) or System.out.println(s);
• The latter prints an “end of line” after s
• The following are equivalent:
(1) System.out.print(s1);
System.out.println(s2);
(2) System.out.println(s1 + s2);
CS100
Lecture 4
12
Flush
• // Flush the output buffer
// Make sure everything is sent to the screen
• System.out.flush();
• Use this when you want to be sure the
output is seen immediately
• println automatically flushes, print does not
• See pp.86-87 of text.
CS100
Lecture 4
13
Now, back to our example
• Accessing fields of an Employee object
Employee c;
c= new Employee();
c.name= “G”;
c.pay= 1000000;
c.hireDate= 1998;
c.pay= 220000;
• Anyone see any problems here? Logically?
CS100
Lecture 4
14
Security Issue
• Allowing access to the pay field means that
any program that can reference c can
change pay.
• This could be bad . . .
• Changing a ‘sensitive’ field like pay should
be limited to methods of the class
• How to do this in Java?
CS100
Lecture 4
15
Public/Private
• // Anyone can access salary
public int salary;
• // Only methods w/in Employee can
// reference pay
private int pay;
• The following is now illegal:
Employee c;
c = new Employee();
c.pay = 1000000;
CS100
Lecture 4
16
So, how to change pay?
• Now to change pay it’s necessary to call the
method setSalary or raiseSalary
• If the methods were declared private, then
this would not be possible except from
within the Class
CS100
Lecture 4
17
Procedures vs. Functions
• Method raiseSalary has prefix void
public void raiseSalary(double p);
• void indicates that it does not return a result
-- a procedure
• Method getName has prefix String
public String getName();
• A non-void prefix indicates that a result is
returned -- a function
CS100
Lecture 4
18
A Function
• // Yield the person’s name
public String getName()
{ return Name; }
• Recall: Executing return <expression> terminates
execution of the method (function) and returns
the value of <expression> to the place of the call
• String s = e1.getName();
• Think of functions in math: f(g(h(x)))
• Can do similar things in Java
CS100
Lecture 4
19
Constructors
• A regular method except:
– its name is the same as the name of the Class
– it has no type class prefix of void
• Use to initialize fields
//Constructor: name n, year d hired, salary s
public Employee(String n, double s, int d)
{name= n; pay= s; hireDate= d; }
• c = new Employee(“millett”, 50000, 1999)
Suuuuuuuure...
CS100
Lecture 4
20
Another class (p. 142 in text)
Class Rectangle {
int length, width;
public Rectangle (int side1, int side2) {
length = side1; width = side2; }
public int area () {
return (length * width);
}
CS100
Lecture 4
21
Use of class Rectangle
int userLength = Integer.parseInt(stdin.readLine());
int userWidth = Integer.parseInt(stdin.readLine());
Rectangle r1;
r1 = new Rectangle(userLength, userWidth);
System.out.println(“The area of your rectangle is: ”);
System.out.println(r1.area());
Rectangle r2 = new Rectangle(5, 10);
if (r2.area() > r1.area()) {
System.out.println(“Your rectangle is smaller.”); }
CS100
Lecture 4
22
What Have We Learned?
•
•
•
•
•
How to define a class -- fields, methods
Definition of a class variable
Creation of a new instance of a class
Referencing and assigning fields
Assigning class instance to class variable to
create an alias
• Class methods
• Class constructors
CS100
Lecture 4
23