1 / 36

AP Computer Science

AP Computer Science. TOPICS TO DISCUSS . equals() == i nstanceof operator compareTo Interfaces Abstract Classes. References and Strings . You can create Strings two different ways.

katima
Télécharger la présentation

AP Computer Science

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. AP Computer Science TOPICS TO DISCUSS .equals() == instanceof operator compareTo Interfaces Abstract Classes

  2. References and Strings You can create Strings two different ways. Using the new keyword to create a String creates a different reference that creating a String without the new keyword. String s = new String(“mom”); String s2 = new String(“mom:”); String s3 = s2; String s4 = “mom”; String s5 = “mom”;

  3. Storing String objects Java has 2 types of memory for Strings. 1st is the POOL Objects without the keyword new are stored in a Pool. Objects created this way that contain the same “String” information and also share the same reference. This saves space in memory. There is one reference and they all share it. String s = “Sun”; String s2 = “Sun”; s == s2 True (same reference ) s.equals(s2) True (same String “Sun”) Sun

  4. Java has 2 types of memory for Strings. HEAP Objects created with the keyword new are stored in a Heap. Objects created this way that contain the same “String” information also share the same reference. However, they do not share the same reference. Each object created this way has its own reference. This saves space in memory. There is one reference and they all share it. String s = new String(“Sun”); String s2 = new String(“Sun”); s == s2 false (not same reference ) s.equals(s2) True (same String “Sun”) s reference Sun s2 reference

  5. "Sun" String reference String reference String reference “Sun" When created this way, Java looks in the pool to see if there is already a String with the same name. If so points to it and has the same reference as other objects with that content. When created WITH THE WORD NEW objects go on the heap. Each object is brand new and has its own reference. It not shared. These are created as new objects and do not have the same reference. Every object created is unique and has its own reference. String s1 = "Sun"; String s3 = “Sun”; String s4 = new String(“Sun“); String s5 = new String (“Sun”); There is only one reference created. All objects share the same reference to the object “Sun”. s1 s4 s5 s3 POOL HEAP

  6. Alias You can assign a String to another String; however and it will contain the same reference. String s = new String(“Sun”); s2 = s; Now there is only one object. s and s2 are aliases of each other. They now share the same reference.

  7. String s1 = "Hello"; // String literal String s2 = "Hello"; // String literal String s3 = s1; // same reference String s4 = new String("Hello"); // String object String s5 = new String("Hello"); // String object

  8. Why does this matter? String comparison: There are three ways to compare String objects: • By equals() method (inherited from Object) • By == operator • By compareTo() method

  9. By equals() method: • Equals() method compares the original content of the String. Does it have the same content. public boolean equals(Object another) public booleanequalsIgnoreCase(String another)

  10. Equality using equals(Object o) • String n = "Computer"; • String s = "Computer"; • String t = new String("Computer"); • String u = new String("Computer"); • String v = new String (“computer”); boolean b = n.equals(s); true boolean b = n.equals(t); true boolean b = n.equals(u); true boolean b = n.equalsIgnoreCase(v); true

  11. String reference String reference “Computer" String reference “Computer" By == operator • String n = "Computer"; • String s = "Computer"; • String t = new String("Computer"); • String u = new String("Computer"); t n u s HEAP POOL

  12. == equality • String n = "Computer"; • String s = "Computer"; • String t = new String("Computer"); • String u = new String("Computer"); String v = u; n == s true n == t false t == u false v==u true

  13. compareTo method parameters intcompareTo(Object o) // Object o is the object to be compared or intcompareTo(String anotherString) // String to be compared What is returned if the two strings are equal to each other returns 0 . if argument is > than String return value < 0 (negative number) if the argument is < than the string return > 0 (positive number) .

  14. Lexicographic order: • Lexicographic order is a generalization of alphabetical order. • In this ordering, numbers come before letters and capital letters come before lower case letters. Lexicographic comparison is like alphabetizing the Strings. • numbers • uppercase • lower case http://ss64.com/ascii.html

  15. Ascii table Notice the Ascii table assigns a decimal value for each character, symbol, uppercase and lowercase letter. This is used in the compareTo method. If you have Apple and apple Apple capital A is 65 Apple lowercase a is 96 Is Apple > apple no 65 – 97 = - 32 Prints negative #

  16. Lexicographical • You can put a - than sign for the compareTo to help see the relationship. • You will not know the exact value of the letter unless you look at the Ascii code. However, you can remember that symbols, upper case and then lowercase order. So uppercase will always have a lower number than the lowercase numbers. • "APPLE".compareTo("apple") returns negative integer. -32 • Argument is greater than String A ascii code of 65 > a ascii code of 97 no 65 - 97 • “apple”.compareTo(“APPLE”) returns positive integer 32 97 – 32 = 32 • argument less than String a ascii code of 97 > A ascii code of 65 yes • “apple”.compareTo(“apple”) returns 0 equal to each other RULES FOR compareTo • if the two strings are equal to each other returns 0 . • if argument is > than String return value < 0 (negative number) • if the argument is < than the string return > 0 (positive number 65 - 97 97 - 65 97 - 97

  17. Return Value : if the two strings are equal to each other returns 0 . if argument is greater than String return value < 0 (negative number) if the argument is less than the string return > 0 (positive number) String str1 = "Abc"; String str2 = "abc"; String str3 = "year"; String str4 = "table"; String str5 = "abc"; System.out.println(str1.compareTo(str2)); System.out.println(str2.compareTo(str1)); System.out.println(str3.compareTo(str4)); System.out.println(str5.compareTo(str2)); “ABC to “abc argument is > so negative -32 “abc to “Abc” argument is < so positive 32 “year” to “”table” argument is < so positive 5 “abc” to “abc” equal returns 0 -32 32 5 0

  18. SuperHero Program public String compareObjectName(SuperHero s1, SuperHero s2) { if(s1.name.compareTo(s2.name) > 0 ) { return s1.getName() + " is lexigraphically after " + s2.getName() + " and returns positive number"; } else if(s1.name.compareTo(s2.name) < 0 ) { return s1.getName() + " is lexigraphically before " + s2.getName() + " and returns negative number"; } else { return “They are the same”; } } lexigraphical # - lexigraphical # = positive SuperHero ironman = new SuperHero(“IronMan”, “Toys”, “Suit”); SuperHero captainAmerica = new CaptainAmerica(“Captain America”, “Shield”, “Strength”, 10); SuperHero captainAmerica2 = new CaptainAmericaCaptain America”, “Shield”, “Strength”, 15); lexigraphical # - lexigraphical # = negative

  19. Calling the compareObjectNames method SuperHero ironman = new SuperHero(“IronMan”, “Toys”, “Suit”); SuperHero captainAmerica = new CaptainAmerica(“Captain America”, “Shield”, “Strength”, 10); SuperHero captainAmerica2 = new CaptainAmerica(“Captain America”, “Shield”, “Strength” 15); System.out.println(h.compareObjectName(ironman, captainAmerica)); (Ironman compared to Captain America > 0) I comes after C lexigraphically so it should return a postivie number. System.out.println(h.compareObjectName(captainAmerica, ironman)); (Captain America compared to Ironman > 0) C comes before I lexigraphically so it should return a negative number System.out.println(h.compareObjectName(captainAmerica, captainAmerica2)); (Captain America compared to Captain America) Captain America == Captain America so it should return the same

  20. Returning 1, -1 or 0

  21. instanceof • The instanceof operator allows you determine the type of an object. It takes an object on the left side of the operator and a type on the right side of the operator 

  22. whatObject(SuperHero h)

  23. Interfaces • A collection of related methods whose headers are provided without implements (no code in the body of the method) • The classes that implement the interface write the code for the method. • The class must implement every method in the interface. Java has several interfaces in its Library. The Swing class which is used to build GUI has interfaces that provide standard methods that must be implemented when using different components such as buttons, checkboxes, radio buttons, and so on.

  24. Mouse Events • One of the interfaces is ItemListener. • Used to listen for events with the mouse. It contains 4 methods which must be implemented in your program when you want to create mouse events. These methods have no implementation. (no body, no code). You create the code to perform the action that you want. Java just wants to keep the method headers that you use standard. I have a tic-tac-toe game I created that demonstrates the implementation of these methods. It is in the news item.

  25. Creating Interfaces public interface Flier { void fly( ); // public by default } You use the keyword interface All methods in the interface have no implementation. They end with a ; They do not have a visibility because the default is public. They must be public because all methods must be implements in the class that implements the interface.

  26. Creating Interfaces public interface Athlete { void train(double hours); } The Athlete interfaces has one method called void train(double hours); that must be implemented in any class that uses (implements this interface).

  27. Class that implements Flier public class Airplane implements Flier { public void fly( ) { System.out.println("Using my jet engines to fly "); } } The Airplane class has implemented the Flier class. You implement an interface by using the keyword implements You must implement all the methods from the interface. It created code (body) for the fly method. (It implemented the fly method)

  28. Class that implements Flier public class Bird implements Flier { public void fly( ) // public must be written here { System.out.println("Using my wings to fly"); } } Bird implements Flier It created code for the method fly (It implemented the method) It does something different from Airplane.

  29. You can implement several interfaces public class SkiJumperimplements Flier, Athlete { private String firstName; private String lastName; private double hoursTraining; private int numberOfJumps; public void fly( ) { System.out.println("Using skis to take me into the air "); } public void train(double hours) { System.out.println("I am on the slopes " + hours + " hours today."); hoursTraining += hours; } } Implemented the fly method from Flier And the train method from Athlete

  30. Interfaces • Interfaces provide abstract methods. Never concrete. All methods in the class have no implementation and end with ; • Interfaces cannot have instance variables. • They can have a public static final variable • INTERFACES CANNOT BE INSTANTIATED. • You cannot create an object from an interface • You can let the interface create the class object. • Flier bird = new Bird();

  31. Abstract • Abstract classes are classes. • Subclasses can extend Abstract classes • Classes can contain concrete and abstract methods (methods with no code). • Abstract classes can have instance variables.

  32. Abstract class Uses the keyword abstract Contains instance variables Has a constructor that the subclasses will use Has concrete classes: getName() double semiPerimeter() Has abstract methods: abstract double area(); abstract double perimeter(); A square and a circle have different ways to figure area and perimeter. So the methods are abstract and will be implemented in the class. public abstract class Shape { private String myName; //constructor public Shape(String name) { myName = name; } public String getName() { return myName; } public abstract double area(); public abstract double perimeter(); public double semiPerimeter() { return perimeter() / 2; } }

  33. Class that extends Shape public class Circle extends Shape { private double myRadius; //constructor public Circle(String name, double radius) { super(name); myRadius = radius; } public double perimeter() { return 2 * Math.PI * myRadius; } public double area() { return Math.PI * myRadius * myRadius; } } Uses the keyword extends Implements all the abstract methods from the Shape class. Uses the super to access name from the constructor. Adds its own instance variable myRadius

  34. Square extends Shape Uses the keyword extends Implements all the abstract methods from the Shape class. Uses the super to access name from the constructor. Adds its own instance variable mySide public class Square extends Shape { private double mySide; //constructor public Square(String name, double side) { super(name); mySide = side; } public double perimeter() { return 4 * mySide; } public double area() { return mySide * mySide; } }

  35. Tester class for Shape import java.util.Scanner; public class ShapeTester { public static void main(String[] args) { //cannot do this: Shape a = new Shape("blob"); // cannot instantiate an abstract class Shape c = new Circle("small circle", 5); Shape circ = new Circle("circle", 3.5); Shape sq = new Square("square", 4); System.out.println("Area of " + circ.getName() + " is " + circ.area()); System.out.println("Area of " + sq.getName() + " is " + sq.area()); Shape s = null; Scanner sc = new Scanner(System.in); System.out.println("Which Shape: circle or square "); String str = sc.nextLine(); if(str.equalsIgnoreCase("circle")) s = circ; else s = sq; System.out.println("Area of " + s.getName() + " is " + s.area()); } } CANNOT INSTANTIATE AN OBJECT OF AN ABSTRACT CLASS. The methods have not code!

  36. Interface vs. abstract class (cont)

More Related