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

Ch. 2 Abstract Data Types and Java Classes

  • Upload
    lydie

  • View
    44

  • Download
    1

Embed Size (px)

DESCRIPTION

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. - PowerPoint PPT Presentation

Citation preview

Page 1: Ch. 2 Abstract Data Types and Java Classes

Ch. 2 Abstract Data Types and Java Ch. 2 Abstract Data Types and Java ClassesClasses

Abstract data typeAbstract data type Object-oriented programmingObject-oriented programming Java class and objectJava class and object Private data and public methodsPrivate data and public methods Accessor v.s. modification methodsAccessor v.s. modification methods Creating and using objectsCreating and using objects Representing and manipulating objectsRepresenting and manipulating objects Java packagesJava packages

Page 2: Ch. 2 Abstract Data Types and Java Classes

I/O Handling -- noteI/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"); } }}

Page 3: Ch. 2 Abstract Data Types and Java Classes

Abstract data typeAbstract data type

A specification of a collection of data that satisfy certain conditions and can be handled A specification of a collection of data that satisfy certain conditions and can be handled and modified in specified waysand modified in specified ways

Example - a list of some data items, prioritized, where one can insert an item at or Example - a list of some data items, prioritized, where one can insert an item at or delete an item from a priority positiondelete an item from a priority position

• You can use this for your shopping list, or for a company’s hiring listYou can use this for your shopping list, or for a company’s hiring list• Wouldn’t a Java vector work for this already?Wouldn’t a Java vector work for this already?• It is abstract, open to different implementationsIt is abstract, open to different implementations

Implementation (program design and coding)Implementation (program design and coding) AnalysisAnalysis Testing and debuggingTesting and debugging Maintenance and updatingMaintenance and updating LegacyLegacy

Page 4: Ch. 2 Abstract Data Types and Java Classes

Object-oriented programmingObject-oriented programming

It is a programming approach where data and tools It is a programming approach where data and tools are associated with or in program entities called are associated with or in program entities called objects, and other programs interact with an object objects, and other programs interact with an object through methods of the object to make things through methods of the object to make things happenhappen

Page 5: Ch. 2 Abstract Data Types and Java Classes

Java class and objectJava class and object

A Java class is a blueprint for implementing a A Java class is a blueprint for implementing a (abstract or concrete application) data type(abstract or concrete application) data type

A Java object is a concrete instance of the class, A Java object is a concrete instance of the class, and of the data type it implementsand of the data type it implements

Example - we can write a List class, and then Example - we can write a List class, and then create different objects of the class, as different create different objects of the class, as different people’s shopping lists, or as lists of different people’s shopping lists, or as lists of different usage (hiring list, etc.)usage (hiring list, etc.)

Page 6: Ch. 2 Abstract Data Types and Java Classes

Java class membersJava class members

Instance variables - they represent and store data in an Instance variables - they represent and store data in an object, often declared privateobject, often declared private

Methods - they are activated to do things, including Methods - they are activated to do things, including handling data, declared public if designed for other handling data, declared public if designed for other classes to useclasses to use

• Instance methods - methods identified with an object; Instance methods - methods identified with an object; each object of the class has its owneach object of the class has its own

• Static methods - class methods, part of the class but not Static methods - class methods, part of the class but not part of an object, sort of the master methods of a part of an object, sort of the master methods of a species (class)species (class)

Page 7: Ch. 2 Abstract Data Types and Java Classes

Example - the Throttle classExample - the Throttle class

Each object of the Throttle class is a concrete Each object of the Throttle class is a concrete throttle, a device for a user to control and regulate throttle, a device for a user to control and regulate water flowwater flow

There is neither real water flow nor real There is neither real water flow nor real mechanical device here, just a mathematical and mechanical device here, just a mathematical and program representation of such thingsprogram representation of such things

The instance methods of an object are invoked to The instance methods of an object are invoked to get things from or do things to an objectget things from or do things to an object

Page 8: Ch. 2 Abstract Data Types and Java Classes

Specification of the Throttle classSpecification of the Throttle class

public class Throttlepublic class Throttle private instance variables:private instance variables: int top /* the max water flow */int top /* the max water flow */ int position /* the current water flow int position /* the current water flow amount */amount */

The constructor method for initializing an object: The constructor method for initializing an object: public Throttle(int size) public Throttle(int size)

/* when a new throttle is created the /* when a new throttle is created the max flow size is given, initial flow max flow size is given, initial flow amount is 0 (no water)*/amount is 0 (no water)*/

Page 9: Ch. 2 Abstract Data Types and Java Classes

Specification of the Throttle classSpecification of the Throttle class

Methods to get data or info from an object:Methods to get data or info from an object: public double getFlow( ) public double getFlow( ) /* what is the flow level 0 ~1 (1 is /* what is the flow level 0 ~1 (1 is 100% of max) */100% of max) */

public boolean isOn( ) public boolean isOn( ) /* is the throttle on, or off (no water /* is the throttle on, or off (no water is off) */is off) */

Page 10: Ch. 2 Abstract Data Types and Java Classes

Specification of the Throttle classSpecification of the Throttle class

Methods to change water flow:Methods to change water flow: public void shift(int amount)public void shift(int amount) /* change the water flow by the amount /* change the water flow by the amount as long as not exceeding max capability as long as not exceeding max capability or below 0*/or below 0*/

public void shutOff( )public void shutOff( ) /*turn off the water flow*//*turn off the water flow*/

Page 11: Ch. 2 Abstract Data Types and Java Classes

Accessor v.s. modification methodsAccessor v.s. modification methods

The methods getflow and isOn are accessor The methods getflow and isOn are accessor methods, accessing data in or with this objectmethods, accessing data in or with this object

The methods shift and shutOff are modification The methods shift and shutOff are modification methods, changing things in or about this objectmethods, changing things in or about this object

Page 12: Ch. 2 Abstract Data Types and Java Classes

Creating and using an object (often Creating and using an object (often from another class)from another class)

Creating an object of a class - invoke a constructor Creating an object of a class - invoke a constructor method of the class with the new keyword:method of the class with the new keyword:

Throttle control = new Throttle(100);Throttle control = new Throttle(100); /* this throttle has a max of 100 flow /* this throttle has a max of 100 flow level positions */level positions */

The throttle is now represented by the variable controlThe throttle is now represented by the variable control Activate a method of this throttle:Activate a method of this throttle: if (!control .isOn( ))if (!control .isOn( )) control .shift(10); /* if off, turn it control .shift(10); /* if off, turn it on */on */

Page 13: Ch. 2 Abstract Data Types and Java Classes

Objects are represented by reference Objects are represented by reference variablesvariables The same object may be represented by several The same object may be represented by several

variablesvariables If an object represented by one variable is assigned If an object represented by one variable is assigned

through that variable to another variable, both through that variable to another variable, both variables refer to the same objectvariables refer to the same object

The equality test ‘The equality test ‘====‘ finds out if two variables refer ‘ finds out if two variables refer to the same object, not if they have the same data to the same object, not if they have the same data content (for primitive data variable, such as int or content (for primitive data variable, such as int or double, there is no object, and it compares the content double, there is no object, and it compares the content values)values)

Page 14: Ch. 2 Abstract Data Types and Java Classes

Passing an object as argument into a Passing an object as argument into a methodmethod

When an object in a variable is given as argument When an object in a variable is given as argument to a method invocation, it is like it has been to a method invocation, it is like it has been assigned to a parameter variable of the method. assigned to a parameter variable of the method. So, the parameter variable in the method still So, the parameter variable in the method still refers to the same object as the outside variablerefers to the same object as the outside variable

When the data content of the object is modified When the data content of the object is modified inside the method, the same changes occur in the inside the method, the same changes occur in the object outside because it is the same objectobject outside because it is the same object

Page 15: Ch. 2 Abstract Data Types and Java Classes

Compare, copy object contentsCompare, copy object contents

Then how can we find out if two objects have the Then how can we find out if two objects have the same content?same content?

And how do we deliver an object to another And how do we deliver an object to another variable in a way that the other variable gets a new variable in a way that the other variable gets a new object of the same content but not the same object of the same content but not the same object?object?

We’ll look at these topics later in this chapterWe’ll look at these topics later in this chapter

Page 16: Ch. 2 Abstract Data Types and Java Classes

The null valueThe null value

The special null value can be assigned to a The special null value can be assigned to a variable that is of an object type; it means the variable that is of an object type; it means the variable is not referring to any concrete object variable is not referring to any concrete object

If an object does not have variables to represent it, If an object does not have variables to represent it, Java execution will discard it and recycle the Java execution will discard it and recycle the computer resourcescomputer resources

If a reference variable has the null value and the If a reference variable has the null value and the program attempts to use the (non-existent) object program attempts to use the (non-existent) object in this variable, there can be null pointer exceptionin this variable, there can be null pointer exception

Page 17: Ch. 2 Abstract Data Types and Java Classes

Java packagesJava packages

The programmer may sometimes like to place The programmer may sometimes like to place related classes in a project into a package, or related classes in a project into a package, or classes for similar use together in a package (like classes for similar use together in a package (like in the Java library)in the Java library)

The top of each file needs to declare the packageThe top of each file needs to declare the package All classes in the package need to reside in a All classes in the package need to reside in a

folder with the same name as the package namefolder with the same name as the package name The Java compiler / interpreter would need to The Java compiler / interpreter would need to

know where the folder isknow where the folder is

Page 18: Ch. 2 Abstract Data Types and Java Classes

The Location class and object The Location class and object manipulationmanipulation

An object of Location class represents a point An object of Location class represents a point (location) in the (x,y) two-dimensional plane(location) in the (x,y) two-dimensional plane

Methods of Location class allows getting data from an Methods of Location class allows getting data from an object as well as modifying data content of the object object as well as modifying data content of the object (shift and rotation)(shift and rotation)

What is more, there is a method to copy an object’s What is more, there is a method to copy an object’s data to make a new object of same datadata to make a new object of same data

And there are methods that work on two Location And there are methods that work on two Location objects: comparing equality of location, obtaining a objects: comparing equality of location, obtaining a new location from two existent ones, etc.new location from two existent ones, etc.

Page 19: Ch. 2 Abstract Data Types and Java Classes

The static distance methodThe static distance method

public static double distance(Location p1, public static double distance(Location p1, Location p2) {Location p2) {

double a, b, c_squared;double a, b, c_squared; if (p1 == null || p2 == null)if (p1 == null || p2 == null) return Double.NaN;return Double.NaN; a = p1.x - p2.x;a = p1.x - p2.x; b = p1.y - p2.y;b = p1.y - p2.y; c_squared = a * a + b * b;c_squared = a * a + b * b; return Math.sqrt(c_squared);return Math.sqrt(c_squared); }}

Page 20: Ch. 2 Abstract Data Types and Java Classes

The static midpoint methodThe static midpoint method public static Location midpoint(Location public static Location midpoint(Location p1, Location p2) {p1, Location p2) {

double xMid, yMid;double xMid, yMid; if (p1 == null || p2 == null) if (p1 == null || p2 == null) return null;return null; xMid = p1.x / 2 + p2.x / 2;xMid = p1.x / 2 + p2.x / 2; yMid = p1.y / 2 + p2.y / 2;yMid = p1.y / 2 + p2.y / 2; Location mid = new Location(xMid, yMid);Location mid = new Location(xMid, yMid); return mid;return mid; }}

Page 21: Ch. 2 Abstract Data Types and Java Classes

The instance shift methodThe instance shift method

public void shift public void shift (double xAmount, double yAmount) {(double xAmount, double yAmount) { x += xAmount;x += xAmount; y += yAmount;y += yAmount; }}

Page 22: Ch. 2 Abstract Data Types and Java Classes

The instance equals methodThe instance equals method public boolean equals (Object obj) {public boolean equals (Object obj) {

if (obj instanceof Location) {if (obj instanceof Location) { Location other = (Location) obj;Location other = (Location) obj; boolean yes = (other.x == x) && boolean yes = (other.x == x) && (other.y = y);(other.y = y); return yes;return yes; }} else else return false;return false; }}

Page 23: Ch. 2 Abstract Data Types and Java Classes

The instance clone methodThe instance clone method

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

return copy;return copy; }}

Page 24: Ch. 2 Abstract Data Types and Java Classes

About the clone methodAbout the clone method1 This method invokes the clone method of the Object This method invokes the clone method of the Object

class to get a copy of the object itself that will be an class to get a copy of the object itself that will be an independent object ; the super keyword is used for the independent object ; the super keyword is used for the reason that the Object class is a parent class (as in reason that the Object class is a parent class (as in inheritance, Ch. 13) of Location, and that Location has inheritance, Ch. 13) of Location, and that Location has its own clone methodits own clone method

2 The try-catch statement covers-catches a possible The try-catch statement covers-catches a possible exception originated in the execution of the super exception originated in the execution of the super clone method; it can prevent the program from ending clone method; it can prevent the program from ending at this point if the exception indeed occursat this point if the exception indeed occurs

Page 25: Ch. 2 Abstract Data Types and Java Classes

About the clone methodAbout the clone method3 For any class to utilize the Object class’ cloning capability, For any class to utilize the Object class’ cloning capability,

the class will have to implement the Cloneable interface; the class will have to implement the Cloneable interface; this is done by declaring in the header of the class: this is done by declaring in the header of the class: implements Cloneable. An interface is something that implements Cloneable. An interface is something that when implemented by a class, the objects of that class can when implemented by a class, the objects of that class can benefit from the mechanism any object of the interface benefit from the mechanism any object of the interface enjoysenjoys

4 In the code of the clone method when a CloneNot-In the code of the clone method when a CloneNot-Supported exception is caught, a new Runtime exception is Supported exception is caught, a new Runtime exception is thrown, with customized message, to indicate that while thrown, with customized message, to indicate that while running an error is discoveredrunning an error is discovered

Page 26: Ch. 2 Abstract Data Types and Java Classes

Static methods, and the Math classStatic methods, and the Math class

To activate a static method, if it is in another class To activate a static method, if it is in another class use: use: classname.methodname(arguments); classname.methodname(arguments); anan object of object of that class is not requiredthat class is not required

The Math class has many useful static methods for The Math class has many useful static methods for mathematical computation, such as pow for mathematical computation, such as pow for raising one number to the power of another, sqrt raising one number to the power of another, sqrt for square root, random for random number, etc.for square root, random for random number, etc.

Page 27: Ch. 2 Abstract Data Types and Java Classes

Static variables, and the NaN valueStatic variables, and the NaN value

A class can have static variables, too. These are A class can have static variables, too. These are member variables but are not instance variables, member variables but are not instance variables, belong to the entire class and can be shared by all belong to the entire class and can be shared by all objects of the classobjects of the class

The double value Double.NaN, is a final static The double value Double.NaN, is a final static variable in the Double class. It means not a variable in the Double class. It means not a number, and would occur, for example, when a number, and would occur, for example, when a program attempts to divide 0 by 0program attempts to divide 0 by 0

Page 28: Ch. 2 Abstract Data Types and Java Classes

Arithmetic overflowArithmetic overflow

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