topic 24 more on classes classes part ii
play

Topic 24 More on Classes Classes Part II Classes are programmer - PowerPoint PPT Presentation

Topic 24 More on Classes Classes Part II Classes are programmer defined data types In Java the primitives (int, char, double, "Object-oriented programming as it emerged boolean) are the core data types already in Simula 67 allows


  1. Topic 24 More on Classes Classes Part II � Classes are programmer defined data types � In Java the primitives (int, char, double, "Object-oriented programming as it emerged boolean) are the core data types already in Simula 67 allows software structure to be defined based on real-world structures, and gives � All other data types are classes, and are programmers a powerful way to simplify the defined by programmers design and construction of complex – even the classes in the Java Standard Library programs. " – look at source code � Classes are another technique for managing - David Gelernter complexity – along with sub programs (methods) and arrays (data structures) Based on slides for Building Java Programs by Reges/Stepp, found at http://faculty.washington.edu/stepp/book/ CS305j Classes II CS305j Classes II 1 2 Introduction to Computing Introduction to Computing Programming Paradigms � Classes are a major part of a style of programming called Object Oriented Programming Instance Methods and � One technique for managing complexity and building correct programs Encapsulation � Not the only one CS305j Classes II 3 CS305j Classes II 4 Introduction to Computing Introduction to Computing

  2. Accessor methods Problem: printability � accessor : A method that returns state of the � By default, println'ing new types of objects prints object, or computes and returns values based on what looks like gibberish: the object's state. Point p = new Point(10, 7); – Unlike mutators, accessors do not modify the state of the System.out.println(p); // Point@9e8c34 object. � We can instead print a more complex String that � example: Write a method named distance in the shows the object's state, but this is cumbersome. Point class that computes and returns the distance System.out.println("(" + p.x + ", " + p.y + ")"); between two Points. (Hint: Use the Pythagorean � We'd like to be able to simply print the object itself Theorem.) and have something meaningful appear. � example: Write a method named // desired: distanceFromOrigin that computes and returns System.out.println(p); // (10, 7) the distance between the current Point and the origin at (0, 0). CS305j Classes II CS305j Classes II 5 6 Introduction to Computing Introduction to Computing Special method toString How toString is used � Now, in client code that uses your new type of objects, you � If you want your new objects to be easily printable, may print them: you can write a method named toString that tells – Example: Java how to convert your objects into Strings as public class UsePoint2 { needed. public static void main(String[] args) { Point p = new Point(3, 8); System.out.println("p is " + p.toString()); � The toString method, general syntax: } public String toString() { } <statement(s) that return an appropriate String> ; OUTPUT: } p is (3, 8) – Example: // Returns a String representing this Point. � Java allows you to omit the .toString() when printing an public String toString() { object. The shorter syntax is easier and clearer. return "(" + this.x + ", " + this.y + ")"; } System.out.println("p is " + p ); CS305j Classes II 7 CS305j Classes II 8 Introduction to Computing Introduction to Computing

  3. Multiple constructors The this keyword � It is legal to have more than one constructor in a � To avoid redundant code, one constructor may call class. another using the this keyword. – The constructors must have different parameters. public class Point { public class Point { int x; int x; int y; int y; public Point() { // Constructs a Point at the origin, (0, 0). this(0, 0); // calls the (x, y) constructor public Point() { } this.x = 0; this.y = 0; public Point(int x, int y) { } this.x = x; this.y = y; public Point(int x, int y) { this.x = x; } this.y = y; } // ... } // ... } CS305j Classes II CS305j Classes II 9 10 Introduction to Computing Introduction to Computing Encapsulation The equals method � It is considered good style to protect your objects' � The == operator essentially does not work as one data fields from being externally modified. might expect on objects: – Fields can be declared private to indicate that no code – Example: outside their own class can change them. Point p1 = new Point(5, -3); – Declaring a private field, general syntax: Point p2 = new Point(5, -3); private <type> <name> ; System.out.println(p1 == p2); // false – Example: � Instead, objects are usually compared with the private int x; equals method. But new types of objects don't have � Once fields are private, they otherwise would not an equals method, so the result is also wrong: be accessible at all from outside. We usually System.out.println(p1. equals (p2)); // false provide accessor methods to see (but not modify) � We can write an equals method that will behave as their values: we expect and return true for cases like the above. public int getX() { return this.x; } CS305j Classes II 11 CS305j Classes II 12 Introduction to Computing Introduction to Computing

  4. Writing an equals method Object practice problem � Create a new type of objects named Circle. � The equals method, general syntax: – A circle is represented by a point for its center, public boolean equals(Object <name> ) { <statement(s) that return a boolean> ; and its radius. – Make it possible to construct the unit circle, } centered at (0, 0) with radius 1, by passing – To be compatible with Java's expectations, the parameter to equals must be type Object (which no parameters to the constructor. means, 'any object can be passed as the parameter'). – Circles should be able to tell whether a given point is – The value that is passed can be cast into your type. contained inside them. – Example: – Circles should be able to draw themselves using a // Returns whether the have the same x/y Graphics. public boolean equals(Object o) { – Circles should be able to be printed on the console, and Point p2 = (Point) o; return this.x == p2.x && this.y == p2.y; should be able to be compared to other circles for } equality. – This is our first version of equals. It turns out there is much more involved in writing a correct equals method CS305j Classes II CS305j Classes II 13 14 Introduction to Computing Introduction to Computing Object practice problem � Create a new type of objects named LineSegment. – A line segment is represented by two endpoints. Advanced Object Features – A line segment should be able to compute its slope (y2-y1)/(x2-x1). – A line segment should be able to tell whether a given point intersects it. – Line segments should be able to draw themselves using a Graphics. – Line segments should be able to be printed on the console, and should be able to be compared to other lines for equality. CS305j Classes II 15 CS305j Classes II 16 Introduction to Computing Introduction to Computing

  5. Default initialization Null object data fields � If you do not initialize an object's data field in its � What about data fields that are of object types? – Recall the initial version of the Point class: constructor, or if there is no constructor, the data public class Circle { field is given a default 'empty' value. Point center; – Recall the initial version of the Point class: double radius; public class Point { } int x; – Example (using the above class): int y; Circle circ = new Circle(); } System.out.println(circ.center); // null – Example (using the above class): Point p1 = new Point(); � Java prints the bizarre output of 'null' to indicate System.out.println(p1.x); // 0 that the circle's center data field does not refer to � This is similar to the way that array elements are any Point object (because none was constructed automatically initialized to 'empty' or zero values. and assigned to it). CS305j Classes II CS305j Classes II 17 18 Introduction to Computing Introduction to Computing The keyword null NullPointerException � null : The absence of an object. � If you try to call a method on a variable storing null, your program will crash with a NullPointerException. – The Java keyword null may be stored into a reference – Example: variable (a variable intended to refer to an object) to Point p = null; indicate that that variable does not refer to any object. System.out.println("p is " + p); System.out.println( p.getX() ); // crash – Example: – Output: Point p1 = new Point(-4, 7); p is null Point p2 = null ; Exception in thread "main" java.lang.NullPointerException +---------------------+ at UsePoint.main(UsePoint.java:9) +---+ | +----+ +----+ | � To avoid such exceptions, you can test for null using == and != . p1 | --+--> | x | -4 | y | 7 | | – Example: +---+ | +----+ +----+ | if (p == null) { System.out.println("There is no object here!"); +---------------------+ } else { +---+ System.out.println(p.getX()); p2 | / | } +---+ CS305j Classes II 19 CS305j Classes II 20 Introduction to Computing Introduction to Computing

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend