1 / 28

Ch. 2 Abstract Data Types and Java Classes

Ch. 2 Abstract Data Types and Java Classes. Abstract data type Object-oriented programming Java class and object Private data and public methods Accessor v.s. modification methods Creating and using objects Representing and manipulating objects Java packages. I/O Handling -- note.

lydie
Download Presentation

Ch. 2 Abstract Data Types and Java Classes

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. Ch. 2 Abstract Data Types and Java Classes • Abstract data type • Object-oriented programming • Java class and object • Private data and public methods • Accessor v.s. modification methods • Creating and using objects • Representing and manipulating objects • Java packages

  2. I/O Handling -- note import java.io.*; class KeyboardNoEx{ public static void main (String[] arg) {// Keyboard input setup to use keyboard.readLine() InputStreamReader reader = new InputStreamReader (System.in); BufferedReader keyboard = new BufferedReader (reader); String name; System.out.print ("Enter your name: "); // prompt System.out.flush(); //needed to control order try{name = keyboard.readLine(); System.out.println (name); } catch(IOException e){ System.out.println("I/O Exception Occurred"); } } }

  3. Abstract data type • A specification of a collection of data that satisfy certain conditions and can be handled and modified in specified ways • Example - a list of some data items, prioritized, where one can insert an item at or delete an item from a priority position • You can use this for your shopping list, or for a company’s hiring list • Wouldn’t a Java vector work for this already? • It is abstract, open to different implementations • Implementation (program design and coding) • Analysis • Testing and debugging • Maintenance and updating • Legacy

  4. Object-oriented programming • It is a programming approach where data and tools are associated with or in program entities called objects, and other programs interact with an object through methods of the object to make things happen

  5. Java class and object • A Java class is a blueprint for implementing a (abstract or concrete application) data type • A Java object is a concrete instance of the class, and of the data type it implements • Example - we can write a List class, and then create different objects of the class, as different people’s shopping lists, or as lists of different usage (hiring list, etc.)

  6. Java class members • Instance variables - they represent and store data in an object, often declared private • Methods - they are activated to do things, including handling data, declared public if designed for other classes to use • Instance methods - methods identified with an object; each object of the class has its own • Static methods - class methods, part of the class but not part of an object, sort of the master methods of a species (class)

  7. Example - the Throttle class • Each object of the Throttle class is a concrete throttle, a device for a user to control and regulate water flow • There is neither real water flow nor real mechanical device here, just a mathematical and program representation of such things • The instance methods of an object are invoked to get things from or do things to an object

  8. Specification of the Throttle class • public class Throttle • private instance variables: • int top /* the max water flow */ • int position /* the current water flow amount */ • The constructor method for initializing an object: public Throttle(int size) • /* when a new throttle is created the max flow size is given, initial flow amount is 0 (no water)*/

  9. Specification of the Throttle class • Methods to get data or info from an object: • public double getFlow( ) • /* what is the flow level 0 ~1 (1 is 100% of max) */ • public boolean isOn( ) • /* is the throttle on, or off (no water is off) */

  10. Specification of the Throttle class • Methods to change water flow: • public void shift(int amount) • /* change the water flow by the amount as long as not exceeding max capability or below 0*/ • public void shutOff( ) • /*turn off the water flow*/

  11. Accessor v.s. modification methods • The methods getflow and isOn are accessor methods, accessing data in or with this object • The methods shift and shutOff are modification methods, changing things in or about this object

  12. Creating and using an object (often from another class) • Creating an object of a class - invoke a constructor method of the class with the new keyword: • Throttle control = new Throttle(100); • /* this throttle has a max of 100 flow level positions */ • The throttle is now represented by the variable control • Activate a method of this throttle: • if (!control .isOn( )) • control .shift(10); /* if off, turn it on */

  13. Objects are represented by reference variables • The same object may be represented by several variables • If an object represented by one variable is assigned through that variable to another variable, both variables refer to the same object • The equality test ‘==‘ finds out if two variables refer to the same object, not if they have the same data content (for primitive data variable, such as int or double, there is no object, and it compares the content values)

  14. Passing an object as argument into a method • When an object in a variable is given as argument to a method invocation, it is like it has been assigned to a parameter variable of the method. So, the parameter variable in the method still refers to the same object as the outside variable • When the data content of the object is modified inside the method, the same changes occur in the object outside because it is the same object

  15. Compare, copy object contents • Then how can we find out if two objects have the same content? • And how do we deliver an object to another variable in a way that the other variable gets a new object of the same content but not the same object? • We’ll look at these topics later in this chapter

  16. The null value • The special null value can be assigned to a variable that is of an object type; it means the variable is not referring to any concrete object • If an object does not have variables to represent it, Java execution will discard it and recycle the computer resources • If a reference variable has the null value and the program attempts to use the (non-existent) object in this variable, there can be null pointer exception

  17. Java packages • The programmer may sometimes like to place related classes in a project into a package, or classes for similar use together in a package (like in the Java library) • The top of each file needs to declare the package • All classes in the package need to reside in a folder with the same name as the package name • The Java compiler / interpreter would need to know where the folder is

  18. The Location class and object manipulation • An object of Location class represents a point (location) in the (x,y) two-dimensional plane • Methods of Location class allows getting data from an object as well as modifying data content of the object (shift and rotation) • What is more, there is a method to copy an object’s data to make a new object of same data • And there are methods that work on two Location objects: comparing equality of location, obtaining a new location from two existent ones, etc.

  19. The static distance method • public static double distance(Location p1, Location p2) { • double a, b, c_squared; • if (p1 == null || p2 == null) • return Double.NaN; • a = p1.x - p2.x; • b = p1.y - p2.y; • c_squared = a * a + b * b; • return Math.sqrt(c_squared); • } It means: not a number Directly access an instance variable of an object

  20. The static midpoint method • public static Location midpoint(Location p1, Location p2) { • double xMid, yMid; • if (p1 == null || p2 == null) • return null; • xMid = p1.x / 2 + p2.x / 2; • yMid = p1.y / 2 + p2.y / 2; • Location mid = new Location(xMid, yMid); • return mid; • } Why null, not NaN? Object, not double number!

  21. The instance shift method • public void shift • (double xAmount, double yAmount) { • x += xAmount; • y += yAmount; • }

  22. The instance equals method • public boolean equals (Object obj) { • if (obj instanceof Location) { • Location other = (Location) obj; • boolean yes = (other.x == x) && • (other.y = y); • return yes; • } • else • return false; • } Method inside an object, taking in another object to compare Need to convert the object (reference) to Location but need to find out first if it can be a Location object

  23. The instance clone method • public Object clone ( ) { • Location copy; • try { • copy = (Location) super.clone(); • catch (CloneNotSupportedException e) { • throw new RuntimeException( • “To clone, Cloneable Interface must be implemented.”);} • return copy; • }

  24. About the clone method • This method invokes the clone method of the Object class to get a copy of the object itself that will be an independent object ; the super keyword is used for the reason that the Object class is a parent class (as in inheritance, Ch. 13) of Location, and that Location has its own clone method • The try-catch statement covers-catches a possible exception originated in the execution of the super clone method; it can prevent the program from ending at this point if the exception indeed occurs

  25. About the clone method • For any class to utilize the Object class’ cloning capability, the class will have to implement the Cloneable interface; this is done by declaring in the header of the class: implements Cloneable. An interface is something that when implemented by a class, the objects of that class can benefit from the mechanism any object of the interface enjoys • In the code of the clone method when a CloneNot-Supported exception is caught, a new Runtime exception is thrown, with customized message, to indicate that while running an error is discovered

  26. Static methods, and the Math class • To activate a static method, if it is in another class use: classname.methodname(arguments); anobject of that class is not required • The Math class has many useful static methods for mathematical computation, such as pow for raising one number to the power of another, sqrt for square root, random for random number, etc.

  27. Static variables, and the NaN value • A class can have static variables, too. These are member variables but are not instance variables, belong to the entire class and can be shared by all objects of the class • The double value Double.NaN, is a final static variable in the Double class. It means not a number, and would occur, for example, when a program attempts to divide 0 by 0

  28. Arithmetic overflow • When an arithmetic operation produces a number larger than the storage limitation of that data type can accept, it is an arithmetic overflow. For integer types, this usually results in a very different number as answer. For floating-point numbers, it would be a value of either Double.POSITIVE_INFINITY or Double.NEGATIVE_INFINITY

More Related