1 / 39

MIT AITI 2003 Lecture 8

MIT AITI 2003 Lecture 8. Class And Object II. Objective. Represent a Point object The state includes point coordinates, a point label, etc. The “behavior” of a point : Finding the x, y properties, finding distance to another point, etc. We want to write our own data type called Point.

joelle
Download Presentation

MIT AITI 2003 Lecture 8

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. MIT AITI 2003 Lecture 8 Class And ObjectII

  2. Objective Represent a Point object The state includes point coordinates, a point label, etc. The “behavior” of a point: Finding the x, y properties, finding distance to another point, etc. We want to write our own data type called Point. A Point is an abstraction that hides all the operations we might want to do with a geometric point.

  3. A Class Defining a New Data Type class Point { // Data Fields (can use all other object types defined) double x; double y; Stringlabel; booleanerrorFlag = false; // initialized Point origin; } _____________________________ Point myPoint = new Point();

  4. Using the New Data Type If no constructor defined in class, you are given Default Constructor Initializes all empty fields of state to 0 or null. Point aPoint = new Point(); aPoint.x = 4.5; aPoint.y = 3.2; aPoint.label = “Point A”; aPoint.origin = new Point(); aPoint.origin.x = 0.0; aPoint.origin.y = 0.0; aPoint.origin.label = “Origin”; aPoint.origin.origin  PROBLEM

  5. Static Keyword 1. Want all Point Objects to share same Origin. Point aPoint = new Point(); Point bPoint = new Point(); aPoint.origin is a separate object from bPoint.origin. SOLUTION: Use static keyword. Now, all Point objects share a common origin: aPoint.origin is same object as bPoint.origin.

  6. How doesthe Static Keyword affect Attributes • When you create a static attribute it “only exists in the class”. Although each new object has that specific variable, that variable is only a reference to the same variable in the class. This means: • For all the objects created from that class the static variable will have the same value in all the objects since they all refer to the same place in the class • If the variables is changed in one of the objects/class this will change this variable in all objects/class since it really only exists in one place.

  7. How doesthe Static Keyword affect Methods • Like static attributes, static methods only exist in the class. • Static methods cannot refer to non-static variables in the class.

  8. Final Keyword 2. Want Origin to never change. Point aPoint = new Point(); aPoint.origin = new Point(); aPoint.origin.x = 0.0; aPoint.origin = new Point();// Bad – Changes origin Want to finalize the origin. SOLUTION: Use final keyword. Now, all Point objects have the same origin that cannot change.

  9. How doesthe final Keyword affect attributes and methods? • It does not let you change the value of a variable after it has been initialized. • A final variable is a constant. • A final method: prevents someone from overriding the method in a subclass (discussed in a later lecture).

  10. Revised Point Class class Point { double x; double y; String label = “node point”; boolean errorFlag = false; // Added a totalPoints field for counting objects. static int totalPoints = 0; static final Point origin = new Point(); }

  11. Review Example: class Point3D • Identify class variables (those belonging to all 3DPoint objects) • Identify instance variables (those particular to each 3DPoint object) • What happens here to p1.x, p2.x, p1.y, p2.y, and p1.z, p2.z • after each statement? • Point3D p1 = new Point3D(); • Point3D p2 = new Point3D(); • p1.x = 1.0; • p1.y = 2.0; • p2.x = 3.0; • p2.y = 4.0; • Point3D.z = 8.2; • p2.z = 9.9; class Point3D { double x; static double y; static final double z = 7.0; }

  12. Adding Constructors class Point { double x, y; Stringlabel = “node point”; booleanerrorFlag = false; static int totalPoints = 0; static final Pointorigin = new Point(0.0, 0.0); // Construct a new Point – Initialize All empty variables (state). Point(double xPos, double yPos) { x = xPos; y = yPos; ++totalPoints; } }// End Class Point

  13. Multiple Constructors class Point { … static int totalPoints = 0; static final Point origin = new Point(0.0, 0.0, “Origin”); // Construct a new Point given coordinates. Point(double x, double y) { this.x = x; this.y = y; ++totalPoints; } // Another overloaded constructor using this keyword. Point(double x, double y, String label) { this(x, y); //calls alternate constructor this.label = label; } } // End Class Point

  14. this Keyword • The this keyword is a referencewithin the class to the object instance that is being created. Inside the class Point, the this reference points to the specific Point object being created. this.x is the same as using the object’s x parameter unmistakably. this() would call the default constructor. this(4.4, 2.8) would call the first constructor. this.doMethod() would call the object’s method.

  15. References/ Constructors Again Using 1st Constructor: Point pointA = new Point(2.3, 4.8); Using 2nd Constructor: Point pointB = new Point(5.0, 8.9, “point label B”); Creating a reference to an object already made: No NEW Object Created: Must be careful: Multiple references may change same object Point getOrigin = Point.origin; Point anotherReferenceToPointA = pointA;

  16. A Picture Representation After 2 Point Objects Created Object A Static Point.totalPoints Shared between all objects. Can Increment as more objects made. Point A = new Point(5.4, 2.8); x = 5.4 y = 2.8 label = “node point” totalPoints = origin = totalPoints = 3; Static Final Point.origin Shared, Cannot Change Object B Point B = new Point(2.0, 3.0); x = 0.0 y = 0.0 label = “Origin” totalPoints = origin = x = 2.0 y = 3.0 label = “node point” totalPoints = origin =

  17. Objects Continued class Main { public static void main(String[] args) { Point A = new Point(2.0, 3.2); A.x = 5.0; Point.totalPoints = 8; // Or… A.totalPoints = 8; } } /**Problem: Same problem as shown in Apple example. Violates the abstraction concept of a Point object. **/

  18. Encapsulation, Preventing Access Want to hide implementation of Point object: We want to work with Points using Point methods, and try to keep data issues under the surface. Type Name POINT Data Fields: x, y, … Keep Hidden new Point(…) getX() getY() getNumberOfPoints() Interface of Object: (Constructor) Methods

  19. REVIEW Private, Public, (Protected), Nothing Specified. Private: Can only access variable or method within the class itself. Public: Can access variable or method everywhere. Protected: (used in inheritance) Nothing Specified: So far, we have not specified any private or public access. This means the variable or method is accessible in the same package (for now, the same as public)

  20. Using Private, Public, (Protected) Access Modifiers public class Point { private double x, y; private Stringlabel = “node point”; private booleanerrorFlag = false; privatestaticint totalPoints = 0; publicstatic finalPoint origin = new Point(0.0, 0.0, “Origin”); // Constructors // If we make a constructor private, we can’t use it outside class. So now the user can only call the second constructor private Point(double x, double y) { this.x = x; this.y = y; ++totalPoints; } public Point(double x, double y, String label) { this(x, y); this.label = label; } }

  21. Access Into Point Object • Which statements can we now perform outside the Point class (e.g. in another class with a main() method) ? • Point p = new Point(4.4, 2.4); • Point p = new Point(4.4, 2.8, “A new Point”); • p.totalPoints = 5; • Point.totalPoints = 5; • p.x = 4; • Point origin = p.origin; • Point.origin = new Point(3.8, 4.4, “New Origin”);

  22. Making Objects Useful: Methods • Now we can create a point object from x, y coordinates and a label, and encapsulate the data. All private fields are hidden. We are given public fields, and public methods. But, we may still want to access private fields (but not change them). So we use functions and methods. • We want to now do useful things with the data using methods/functions. Function declarations follow: Access static/final return type function name and arguments public double getX() public double getY() public string getLabel() public static int getNumberOfPoints() public double distanceTo(Point pointTwo)

  23. Methods / Functions Review FUNCTION returnType answer Arguments 1…N Type1 arg1 Type2 arg2 … TypeN argN Function: Returns distance from this to pointTwo distanceTo double distance Point pointTwo

  24. public class Point { public double getX() { return x; } public double getY() { return y;} public String getLabel() { return label; } public static int getNumberOfPoints() { return totalPoints;// totalPoints is a static data field. } public double distanceTo(Point pointTwo) { if if (pointTwo == null) { errorFlag = true; // Better: throw a runtime exception. return 0.0; } } // Pythagorean Theorem double xDis = (x - pointTwo.x); double yDis = (y – pointTwo.y); return Math.sqrt(xDis * xDis + yDis * yDis); } } // End Class Point

  25. Using the Methods • Here are sample uses of the Point methods. What is printed out? Point pOne = new Point(4.5, 5.5, “node point One”); Point pTwo = new Point(3.3, 3.3, “node point Two”); System.out.println(“Including origin, we made ” + Point.getNumberOfPoints() + “ points.”); System.out.println(“Distance from ” + pOne.getLabel() + “ to “ + pTwo.getLabel() + “ equals: ” + pOne.distanceTo(pTwo) );

  26. Methods Automatically Given From Object (SuperClass) Methods for All Objects: toString(), equals(), getClass(), hashCode(), notify(), notifyAll(), wait() Object (Base Class) For Our Point Class: We may want to override or redefine toString() equals() Must use same function declaration As specified in super class Object. Point Derived Class

  27. public class Point { // Data Fields … // Constructors … // New Methods … // Overriden Methods (function declarations found in Object super class). public boolean equals(Object pTwo) { if (pTwo == null) return false; if (!(pTwo instanceof Point)) return false; Point pointTwo = (Point) pTwo; return ( (pointTwo.x == x) && (pointTwo.y == y) && (pointTwo.label.equals(label)) ); } public String toString() { return label + “: “ + Double.toString(x) + “, “ + y; } } // End Class Point

  28. public class Point { // Data Fields private double x, y; private Stringlabel = “node point”; private booleanerrorFlag = false; privatestaticint totalPoints = 0; publicstatic finalPoint origin = new Point(0.0, 0.0, “Origin”); //Constructors private Point(double x, double y) {} public Point(double x, double y, String label) {} // New Methods public double getX() {} public double getY() {} public String getLabel() {} public static intgetNumberOfPoints(){} public double distanceTo(PointpointTwo) {} // Overriden Methods public boolean equals(Object pointTwo) {} public String toString() {} } // End Class Point POINT x y label totalPoints errorFlag origin +getX() +getY() +getNumberOfPoints() +distanceTo(Point two) +equals(Object two) +toString()

  29. Review Have finished a simple representation of a Point. We have created our own Point type. We can now understand Java object types better. These are classes someone else wrote for us. We can just use these objects and manipulate them using methods given to us. We do not have to know about their detailed code implementation. Browse : java.sun.com for Java 1.3 or 1.4 API for various java classes that are helpful.

  30. A Helpful Java Defined Type: A Vector import java.util.Vector A Vector class holds elements of type Object. It is the same as an array,but can expand automatically if more objects are inserted, and can hold any type of Object. Vector points = new Vector(); // Define empty Vector. // Vector with 100 elements, but can expand. Vector points = new Vector(100);

  31. Vector Methods import java.util.Vector A Few Important Methods Provided For Us: // returns number of Objects stored in the Vector. int size() { …. } // adds a new object to this Vector list of objects. void addElement(Object newObject) { …. } // returns object at index i of this Vector list. Object elementAt(index i) { …. }

  32. Vector Example import java.lang.Vector public class SimpleVectorApplication { public static void main(String[] args) { Vector points = new Vector(); Point a = new Point(1.0, 1.0); Point b = new Point(2.0, 2.0); Point c = new Point(3.0, 3.0); points.addElement(a); points.addElement(b); points.addElement(c); for (int k=0; k < points.size(); k++) { System.out.println( points.elementAt(k) ); } }

  33. Independent Study Questions

  34. Problem 1: Private/Public Concept class SingletonPoint { private String name = “Only One Object Made Of Type ME”; private static final singleton = new SingletonPoint(); private SingletonPoint() { } public static SingletonPoint getInstance() { return singleton; } public String getName() { return name; } } Above – How can we use the SingletonPoint object if the constructor is private?

  35. Prob 2: Abstract Data Type- IntSet • Want to represent a set of integers (x1, x2, …xN) Goal is to manipulate a set of integers. From Programming Data Abstractions: Liskov, Barbara.

  36. Prob. 2: Abstract Data Type- IntSet • Want to represent a set of integers (x1, x2, …xN) public class IntSet { public IntSet() public void insert(int x) public void remove(int x) public boolean contains(int x) public int size() public boolean isSubsetOf(IntSet s) } From Programming Data Abstractions: Liskov, Barbara.

  37. Problem 3: Bank Accounts • Want to represent a BankAccount Object: Goal is to have a bank account object with methods such as deposit, withdraw, transfer to another bank account, etc. public class BankAccount { private double savings = 0.0; private int accountID = 0; public BankAccount(accountID) {} public boolean withdraw(double amount) { } public void deposit(double amount) {} public boolean transferTo(BankAccount other) {} }

  38. Problem 3 Continued…. • BankAccount Object: Once we have an account object, we can think in an object oriented way to design larger programs and systems. To write a bank account application, we think about: • A Bank Type to represent banks. • Maybe want a Transaction object. (A Transaction is between a Bank and a Person with an Account). • To finish the application – probably need a bank database/file to deal with storing account info. (File IO introduced soon). • Could make a GUI (graphics interface) for someone to access account info on web. Synchronization problems, security, etc.

  39. Intro To Objects END Well designed Objects are the building blocks for larger object oriented systems. Now, our goal is to write larger programs that utilize many objects.

More Related