lecture 4: methods, classes, and objects tami meredith

53
CSCI1227 Computer Programming and Problem Solving Lecture 4: Methods, Classes, and Objects Tami Meredith

Upload: rodger-ross

Post on 19-Jan-2016

224 views

Category:

Documents


0 download

TRANSCRIPT

Slide 1

CSCI1227Computer Programming andProblem Solving Lecture 4: Methods, Classes, and Objects Tami MeredithOverviewObjectsClasses, objects, and instancesConstructorsADTsScopeTypesOverloading

ExerciseWrite a method called nthLargest that has as its parameters an integer n and an array of integers. It returns the nth largest of the integers. That is, if n is 1 it returns the largest, if n is 2 it returns the second largest, and so on.

Solutionpublic static int nthLargest(int n, int[] vals) { if ((n > vals.length) || (n < 1)) { System.out.println("Error: Array bounds violation."); System.exit(0); } Arrays.sort(vals); return (vals[vals.length-n]);} newint x;x = 4;

Scanner input; y = new Scanner(System.in);

Objects store references.Objects are copies of the entire class.Objects have "instance" data that only the specific object can access.

x4sourcenexthasNext()etc. system.in{...}{...}{...}inputreferenceReferencesJava has a few Primitive Typese.g., int, double, boolean, char, voidEverything else is an ObjectAn array is an object: length is an instance variableA String is an array of char: length is an instance methodALL Objects use referencesReferences are just memory addresses/locations

Variables that store Strings, Arrays, Objects all store REFERENCESClasses and ObjectsAn object is an instance of a classEach object is an (almost) complete copy of the classThe class is the type, it is a template.Variables store (references to) instances of objectsThe entire class is copied except for static membersStatic members are shared among all copies/instances of the classUsing ObjectsWhen we want to call a static method or access a static variable, we need to use the name of the classWhen we want to call an instance method or access an instance variable, we need to use the name of the instance that is, the name of the variable that stores it reference If we leave off the name, we mean "in this file"Static VariablesSometimes called Class VariablesOnly one copy of the variable exists for each classE.g.:public static final int HST = 15;Why have more than one copy of HST?Can also have non-final class variablesUseful for sharing information between instancesStatic MethodsOnly one copy exists for the classIs not associated with any instanceUse the class name, not the instance name, to call a static methodCannot access ANY n0n-static class data or non-static methods (without an object)main is always static as we have seenstatic EntitiesInstance Variables: Non-static, each instance of the object gets its own copy of the variable, accessed via the object (instance) nameClass Variables: Static, all instances of the object share the same copy, accessed via the class nameInstance Methods: Non-static, can access the instance variables of the object (as well as the static data)Class Methods: Static, can only access static data in the classSystem.out.print|ln|fSystem is a class that is automatically instantiated by the JVMIt is actually java.lang.Systemout is a static variable of type PrintStreambecause out is static, we use the class name (i.e., System) to access this variableeverything in System is static so we don't need to know what the JVM calls the variable that references Systemprint is the method we want to useprint is an instance method, and thus we need the name of the variable that stores the instance of PrintStream

A Simple Examplepublic class Doll {

// data String name; // Doll's name char sex; // 'f' or 'm' int year; // Year we got doll

// methods public void display() { System.out.printf("Name: %s\n", name); System.out.printf("Sex: %smale\n", (sex == 'f') ? "fe" : ""); System.out.printf("Age: %d\n", 2013-year); }

} // end of class DollExerciseCreate a class to store a playing cardPlaying cards have a suit (club, spade, diamond, heart) and a value (1-10,Jack, Queen, King).Your class should have:an init method, anda display method.Solutionpublic class card { hidden String s, v;

public void init(String suit, String value) { s = suit; v = value; }

public void display() { System.out.printf("%s of %s", v, s); }}Types are Templatesint[] data = new int[10];Scanner keyboard = new Scanner(System.in);Doll barbie = new Doll();

data is a variable of type int[]keyboard is a variable of type ScannerScanner is a library class barbie is a variable of type DollDoll is a user defined class

Remember: A class is a type!Instantiation (Again)Instantiation is when we define an instance of a typeint x; instantiates x as a variable of type intDoll skipper = new Doll();Instantiates skipper as a (reference) variable of type Dollnew makes a new copy of Doll and stores the location (i.e., the reference) of that copy into skipper

Object Types (Summary)A "class" is the "type" of an objectAn "object" is an instance of the class/type

Doll barbie = new Doll();

Doll is a classThe variable barbie is an instance of the class Dollbarbie is of type Dollbarbie contains a reference to a memory location big enough to hold all the data for a DollClasses/types are templates they describe something but have no memory

Using a Classpublic class barbies { public static void main (String[] a) {

Doll d1 = new Doll();

d1.name = "Barbie"; d1.sex = 'f'; d1.year = 2000;

d1.display();

} // end main} // end class barbiesd1ref.namesexyeardisplayBarbief2000{...}newgets memory for the objectcauses a whole COPY of the class to occurScopeEverything with a name has a "scope"Scope is a fancy word that means "the places it can be used"a synonym for "visibility"The scope of a named entity is mostly dependent upon where it is defined (but other things can affect it)Curly Braces { and } control scope! (mostly ...)Method Scopepublic static void two () { int x = 2; System.out.println (x); // prints 2}

public static void main (String[] a) { // Different method, different scope, different x int x = 1; System.out.println (x); // prints 1 two(); // prints 2}Local VariablesLocal variables are variables created inside of a methodTheir scope (visibility) is only inside of the method they cant be used from another methodIf two methods want to share something they must either communicate it using a parameter or it must be an instance/class variableBlocks (any group of statements inside { and }) have their own scopeBlock Scopingpublic static void main (String[] a) { int x = 1; System.out.println("x is: " + x); x is 1 { // new block, new scope int x = 2; System.out.println("x is: " + x); x is 2 } // block ends, scope ends System.out.println("x is: " + x); x is 1} // end mainClass Scopepublic class example { // Scope begins! public static int one () { return (1); } public static void main (String[] a) { System.out.println(one()); // one() is in scope // println() is in the scope of System.out }} // class ends, scope ends!Publicpublic is a scope modifierpublic means the variable or method can be seen (and used) outside of this classCan only be assigned to members of a classThe opposite of public is privateprivate means that the variable or method can only be used inside of the classprivate HIDES THINGS so that they can ONLY BE USED INSIDE THE CLASSA Classpublic class point {

// Private data -- HIDDEN private int[] values = new int[2];

// Setters Store things public void set (int x, int y) { values[0] = x; values[1] = y; } public void setX(int v) { values[0] = v; } public void setY(int v) { values[1] = v; }

// Accessors Get values public int getX() { return (values[0]); } public int getY() { return (values[1]); }

// Useful methods public void sum (point p) { values[0] += p.getX(); values[1] += p.getY(); } public void display() { System.out.printf( "(%d,%d)", values[0], values[1]); }} // end class pointUsing our classpublic class test { public static void main (String[] a) { point p1 = new point(); point p2 = new point(); p1.set(10, 20); p2.set(-5, -6); p1.sum(p2); p1.display();} // end class testConstructorsnew assigns memory spacenew also runs the "constructor"A constructor is a method with the same name as the classThe constructor is used to "set up" the classConstructors can take parameters

Adding a constructorpublic class point {

// Private data -- HIDDEN private int[] values = new int[2];

// Constructor public point (int x, int y) { values[0] = x; values[1] = y; }

// Setters Stores values public void setX(int v) { values[0] = v; } public void setY(int v) { values[1] = v; }

// Accessors Get values public int getX() { return (values[0]); } public int getY() { return (values[1]); }

// useful methods public point sum(point p) { return (new point( values[0]+p.getX(), values[1]+p.getY())); } public void display() { System.out.printf( "(%d,%d)", values[0], values[1]); }} // end class pointUsing our constructorpublic class test2 { public static void main (String[] a) { point p1 = new point(10, 20); point p2 = new point(-5, -6); point p3 = p1.sum(p2); p3.display();} // end class test2ExerciseWrite a method named divide that takes two integers as parameters and returns the quotient AND the remainder (both as integers) of the division.Solutionpublic class pair { int a, b; pair (x, y) { a = x; b = y; }}

public static pair divide (int x, int y) { return (new pair(x/y, x%y));}Abstract Data Typesa point is an example of an abstract data typeIt is abstract because how the data is stored is hiddenE.g.,int[] values = new int[2]; int x, y; long c1, c2;We provide methods to access/set/use the dataThe methods hide how the data is actually storedExamples of ADTspoints, vectors, matricesdeck of cards, chess pieces, game characterlist, stack, queuetree (hierarchy), graphbank account, bank customerScanner, PrintStream

Many more exist Courses on Data Types/StructuresPart of the foundation of OOP, but existed before OOPADT PropertiesHides how the data is storedAll data manipulation is done with the provided methodsChanging how the data is stored only affects the methods in the class, not any method in any other classHow the methods work does not matter to the person who calls the method they just need to know its parameters and return valueCan rewrite the methods without changing any of the places where they are used

Separation of "interface" and "implementation"Information HidingThe concept of separating how to use some code (its interface) from how it works (its implementation)Consider programmers working together on a web browserPat uses functions written by Jean, does not need to know how they work, just how to use themJean writes the code that Pat uses, keeps the details hidden so that Pat only needs to understand how to use itAbstractionA view of something with some of the details removedCarHonda CivicHonda Civic with CVC 1800 engineHonda Civic with Model 8806 Synchromesh Transmission, CVC 1800 engine, and engine rebored 5 thousands over specWe dont need all these details to use the car effectivelyOnly need the details to actually build/repair itEqualityThe == operator tests that two things have the same bit patternApplied to two things of the same typeReference types (e.g., classes) store addresses/locations so == only tests to see if two things are stored in the same locationNormally, we consider two instances equal when their instance variables store the same thingsWe create our own equals() method to do this testingEquality Examplepublic class point {

// instance variables private int[] values = new int[2]; // Equality public boolean equals (point other) { if ((values[0] == other.values[0]) && (values[1] == other.values[1])) return (true); } return (false); }} // end of class pointExerciseWrite a method called equals that takes two arrays of integers as parameters and returns true if the arrays are the same and false otherwise.Solutionpublic static boolean equals (int[] a1, int[] a2) { if (a1.length != a2.length) return (false); for (int i = 0; i < a1.length; i++) { if (a1[i] != a2[i]) return (false); } return (true);} thisCan only be used in an object (i.e., an instance of a class)Means this instance of the class

public void setX(int v) { this.values[0] = v;}

public boolean equals (point other) { if ((this.values[0] == other.values[0]) && (this.values[1] == other.values[1])) return (true); } return (false);}

nullThe value null represents the value 0 (zer0)It is used when an address (reference type) is needed but not knownString line = null;It can be used with every class in assignmentOnly serves to provide a temporary valueCould use it instead of the empty string to signify an error or failure TypesAll data has a typeThe type of an object is its classMethods have types based on their parameters and return valueThe type of a method is sometimes referred to as the methods signaturepublic static void main (String[] args)String[] voidExerciseConsider the point class we developed. Write a method called compareTo, that is a member of the class, and that has the following signature: point inte.g., public int compareTo(point p)The method compares two points and returns a negative value if the point comes first, zero if they are the same, and a positive value if the parameter p comes first. Since a point has two parts (an x and a y), we can use the distance from the origin to compare them using a single value: distance = Math.sqrt((x*x)+(y*y));

Solutionprivate static double distance (int a, int b) { return (Math.sqrt((a*a)+(b*b)));}public int compareTo (point p) { double d1 = distance (this.getX(), this.getY()); double d2 = distance (p.getX(), p.getY()); if (d1 > d2) return (-1); else if (d1 < d2) return (1); else return (0);}

OverloadingWhen two methods have the same name but different type signatures we say that the method is overloadedWe have seen this before with built-in operators like +int, int intfloat, float floatstring, string stringWe can do this for methods we write as well!At least one of the parameters must be different if we overload a methodOverloadingpublic class student {

// instance variables, only seen in class private String name; private int anum;

// constructor public student (String n, int a) { name = n; anum = a; }

// OVERLOADED methods public void initialise(String n) { name = n; } // String -> void public void initialise(int a) { anum = a; } // int -> void public void initialise(int a, String n) { anum = a; name = n; } // (int, String) -> void

public String getName () { return (name); } // accessor public int getANumber () { return (anum); } // accessor

public void display() { System.out.println("Name (A + anum + ): " + name); }} // end of class studentOverloadingMethods must have unique signaturesThe number of parameters must differ The type of at least one parameter must differReturn types can differ, but differences ONLY in return types is not permittedOverloading is applied before automatic type conversion (coercion)An error public void m1 (double x, int y) { }public void m1 (int x, double y) { }

m1 (1.0, 1); // uses first definitionm1 (1, 1.0); // uses second definitionm1 (1, 1); // ERRORm1 (((double) 1), 1); // uses first definitionOverloading is Good!Programmers just need to remember one name not one for each set of parametersE.g., Arrays.sort(...)

static void sort(byte[]a) Sorts the specified array into ascending numerical order.static void sort(byte[]a, intfromIndex, inttoIndex) Sorts the specified range of the array into ascending order.static void sort(char[]a) Sorts the specified array into ascending numerical order.static void sort(char[]a, intfromIndex, inttoIndex) Sorts the specified range of the array into ascending order.static void sort(double[]a) Sorts the specified array into ascending numerical order.static void sort(double[]a, intfromIndex, inttoIndex) Sorts the specified range of the array into ascending order.static void sort(float[]a) Sorts the specified array into ascending numerical order.static void sort(float[]a, intfromIndex, inttoIndex) Sorts the specified range of the array into ascending order.static void sort(int[]a) Sorts the specified array into ascending numerical order.static void sort(int[]a, intfromIndex, inttoIndex) Sorts the specified range of the array into ascending order.static void sort(long[]a) Sorts the specified array into ascending numerical order.static voidsort(long[]a, intfromIndex, inttoIndex) Sorts the specified range of the array into ascending order.static void sort(Object[]a) Sorts the specified array of objects into ascending order, according to the natural ordering of its elements.static void sort(Object[]a, intfromIndex, inttoIndex) Sorts the specified range of the specified array of objects into ascending order, according to the natural orderingof its elements.static void sort(short[]a) Sorts the specified array into ascending numerical order.static void sort(short[]a, intfromIndex, inttoIndex) Sorts the specified range of the array into ascending order.static void sort(T[]a, Comparator