Lecture Notes – Classes and Objects (Ch 7-8) Yonglei Tao.

24
Lecture Notes – Classes and Objects (Ch 7-8) Yonglei Tao

Transcript of Lecture Notes – Classes and Objects (Ch 7-8) Yonglei Tao.

Page 1: Lecture Notes – Classes and Objects (Ch 7-8) Yonglei Tao.

Lecture Notes – Classes and Objects (Ch 7-8)

Yonglei Tao

Page 2: Lecture Notes – Classes and Objects (Ch 7-8) Yonglei Tao.

Arrays Hold sequences of values of primitive types or

objects When an array is created, its values are

initialized zero, false, or null

int [] scores;scores = new int [10];for (int i = 0; i < scores.length; i++)

scores[i] = i * i; for (int n: scores) // a “for each” loop

System.out.println (n);

Page 3: Lecture Notes – Classes and Objects (Ch 7-8) Yonglei Tao.

Arrays (Cont.)String[] names = {“Ed”, “Bob”, “Cindy”};System.out.println( names[0] );if ( names[0].equals(“Ed”)) …

String[] list = new String[5];list[0] = new String(“Tom”);…

A two-dimensional array

int rows = 10, cols = 20;int [][] table = new int[rows][cols];

Page 4: Lecture Notes – Classes and Objects (Ch 7-8) Yonglei Tao.

Partially Filled Arrays - Loadingint numValues = 0;Scanner in = new Scanner(System.in);while (in.hasNextDouble()) { if (numValues < values.length) { values[numValues] = in.nextDouble(); numValues ++; }}

for (int i = 0; i < numValues; i++) { System.out.println(values[i]);}

Page 5: Lecture Notes – Classes and Objects (Ch 7-8) Yonglei Tao.

Class ArrayList A sequence of objects

Can grow and shrink as needed A generic class with a type parameter

ArrayList<String> classlist = new ArrayList<String> ();classlist.add ( “Ed” );classlist.add ( “Bob” );classlist.add ( “Cindy” );

Page 6: Lecture Notes – Classes and Objects (Ch 7-8) Yonglei Tao.

ArrayList (Cont.)

for (int i = 0; i < classlist.size(); i++ ) {String name = classlist.get(i);System.out.println (name); // Ed, Bob, Cindy

}

for ( String name: classlist )System.out.println (name);

classlist.set (1, “Tim”); // Ed, Tim, Cindyclasslist.add (1, “Ron”); // Ed, Ron, Tim, Cindyclasslist.remove (2); // Ed, Ron, Cindy

Page 7: Lecture Notes – Classes and Objects (Ch 7-8) Yonglei Tao.

Wrapper Classes

Page 8: Lecture Notes – Classes and Objects (Ch 7-8) Yonglei Tao.

Auto Boxing and Unboxing

int n = 25;Integer num = n; // same as num = new Integer (n);Double rate = 5.25;double d = rate;rate = rate + i;Boolean isDone = new Boolean(false);

ArrayList<Double> values = new ArrayList<Double>(); values.add(29.95); double x = values.get(0); // inefficient

Page 9: Lecture Notes – Classes and Objects (Ch 7-8) Yonglei Tao.

Arrays vs. ArrayLists When do you use which?

Element type Number of elements Basic operations

Locate insert (at the front, in the middle, at the end) delete (the first, a middle one, the last)

Page 10: Lecture Notes – Classes and Objects (Ch 7-8) Yonglei Tao.

Common Array Algorithm - Search

int pos = 0; boolean found = false; while (pos < values.size() && !found) { if (values.get(pos) > 100)

{ found = true; } else

{ pos++; } } if (found)

{ System.out.println("Position: " + pos); } else

{ System.out.println("Not found"); }

Page 11: Lecture Notes – Classes and Objects (Ch 7-8) Yonglei Tao.

Common Array Algorithm - Insert• ArrayList: use method add

• Unordered array:

if (numValues < values.length) { values[numValues] = newElement; numValues++; }

Page 12: Lecture Notes – Classes and Objects (Ch 7-8) Yonglei Tao.

Common Array Algorithm - Insert Ordered array:

if (numValues < values.length) { for (int i = numValues ; i > pos; i--) values[i] = values[i - 1];

values[pos] = newElement; numValues ++; }

Page 13: Lecture Notes – Classes and Objects (Ch 7-8) Yonglei Tao.

Common Array Algorithm – Array Copy

double[] values = new double[6];

. . . // Fill array

double[] prices = values; ?

double[] prices = Arrays.copyOf(values, values.length);

values = Arrays.copyOf(values, 2 * values.length);

Page 14: Lecture Notes – Classes and Objects (Ch 7-8) Yonglei Tao.

Classes Each has a responsibility Each provides services for clients Objects are instances of a class

Members Instance variables private Instance methods private Instance methods public - interface

Page 15: Lecture Notes – Classes and Objects (Ch 7-8) Yonglei Tao.

Method Call A call

obj.doIt (num, name);

Method definition

public void doIt (int n, String s) {n += 4;System.out.println (“Start with “ +

s.charAt(0));}

Every thing is passed by value What if having s = “Mr. “+ s; in method doIt()?

“tom”

6

6

Page 16: Lecture Notes – Classes and Objects (Ch 7-8) Yonglei Tao.

Overloaded Methods // Methods of class MyClass

public void doIt (int n) { … }public void doIt (char c) { … } public void doIt (int n, String s) { … }

// Method callsMyClass obj = new MyClass();obj.doIt(5);obj.doIt(‘a’);obj.doIt(“xyz”);

Page 17: Lecture Notes – Classes and Objects (Ch 7-8) Yonglei Tao.

Constructorspublic class A {

private int num;private String name;

public A () { this(10,

“tom”);}public A (int n) {

num = n; }public A (int n,

String s) {num = n;

name = s;}…

}

// use of constructors

A ref1 = new A();

A ref2 = new A(5);

A ref3 = new A(10, “tom”);

Page 18: Lecture Notes – Classes and Objects (Ch 7-8) Yonglei Tao.

Static Members of a Class Instance variable

One copy per object Static variable

One copy per class Static Method

Operating on class-wide data

Examples Integer.MAX_VALUE, Integer.MIN_VALUE Math.pow(x, y), Math.sqrt(x)

Page 19: Lecture Notes – Classes and Objects (Ch 7-8) Yonglei Tao.

Scope of Local Variables

public class RectangleTester {

public static double area(Rectangle rect) { double r = rect.getWidth() * rect.getHeight(); return r; }

public static void main(String[] args) { Rectangle r = new Rectangle(5, 10, 20, 30);

double a = area(r); System.out.println(r); }

}

Page 20: Lecture Notes – Classes and Objects (Ch 7-8) Yonglei Tao.

Scope of Local Variables

if (x >= 0) { double r = Math.sqrt(x); ... } // Scope of r ends here else { Rectangle r = new Rectangle(5, 10, 20, 30); // OK - it is legal to declare another r here ... }

Page 21: Lecture Notes – Classes and Objects (Ch 7-8) Yonglei Tao.

Overlapping Scope

public class Coin {... public double getExchangeValue(double exchangeRate) {

double value; ... return value;

}

private String name; private double value; }

Which one to refer to if using value in this method? How to refer to instance variable value in this

method?

Page 22: Lecture Notes – Classes and Objects (Ch 7-8) Yonglei Tao.

Built-in Reference this Referring to an object from within

public A (int num, String name) {

this.num = num;

this.name = name;

} Referring to the current object

A x = new A(10, “bob”);

A y = new A(5, “ed”);

x.setNum(1);

Page 23: Lecture Notes – Classes and Objects (Ch 7-8) Yonglei Tao.

Packages in Java

Package Purpose Sample Class

java.lang Language support Math

java.util Utilities Random

java.io Input and output PrintStream

java.awt Abstract Windowing Toolkit Color

java.applet Applets Applet

java.net Networking Socket

java.sql Database Access ResultSet

javax.swing Swing user interface JButton

omg.w3c.dom Document Object Model for XML documents

Document

Page 24: Lecture Notes – Classes and Objects (Ch 7-8) Yonglei Tao.

Packages - Organizing related classes• To put classes in a package

package cis500.proj1;

public class MyClass { ... }

• To use class with importing

import cis500.proj1.MyClass;

• Or import cis500.proj1.*;