Presentation is loading. Please wait.

Presentation is loading. Please wait.

AP Computer Science TOPICS TO DISCUSS.equals() == instanceof operator compareTo Interfaces Abstract Classes.

Similar presentations


Presentation on theme: "AP Computer Science TOPICS TO DISCUSS.equals() == instanceof operator compareTo Interfaces Abstract Classes."— Presentation transcript:

1 AP Computer Science TOPICS TO DISCUSS.equals() == instanceof operator compareTo Interfaces Abstract Classes

2 References and Strings String s = new String(“mom”); String s2 = new String(“mom:”); String s3 = s2; String s4 = “mom”; String s5 = “mom”; 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. 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.

3 Storing String objects Java has 2 types of memory for Strings. 1 st 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”) 10-3 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 s reference Sun String s = new String(“Sun”); String s2 = new String(“Sun”); s == s2 false (not same reference ) s.equals(s2) True (same String “Sun”) s2 reference

5 10-5 String s1 = "Sun"; String s3 = “Sun”; String s4 = new String(“Sun“); String s5 = new String (“Sun”); s1 s4 s5 "Sun" String reference There is only one reference created. All objects share the same reference to the object “Sun”. String reference “Sun" s3 These are created as new objects and do not have the same reference. Every object created is unique and has its own reference. 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. POOL When created WITH THE WORD NEW objects go on the heap. Each object is brand new and has its own reference. It not shared. 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 10-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: 1.By equals() method (inherited from Object) 2.By == operator 3.By compareTo() method 10-8

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 boolean equalsIgnoreCase(String another) 10-9

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 10-10

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

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 10-12

13 compareTo method parameters int compareTo(Object o) // Object o is the object to be compared or int compareTo(String anotherString) // String to be compared What is returned 1.if the two strings are equal to each other returns 0. 2.if argument is > than String return value < 0 (negative number) 3.if the argument is 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

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 “apple”.compareTo(“APPLE”) returns positive integer – 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 1.if the two strings are equal to each other returns 0. 2.if argument is > than String return value < 0 (negative number) 3.if the argument is 0 (positive number

17 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 Return Value : 1.if the two strings are equal to each other returns 0. 2.if argument is greater than String return value < 0 (negative number) 3.if the argument is less than the string return > 0 (positive number)

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 # = negative 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); SuperHero ironman = new SuperHero(“IronMan”, “Toys”, “Suit”); SuperHero captainAmerica = new CaptainAmerica(“Captain America”, “Shield”, “Strength”, 10); SuperHero captainAmerica2 = new CaptainAmericaCaptain America”, “Shield”, “Strength”, 15);

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); 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 SkiJumper implements 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 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 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; } } 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.

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 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; } 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

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) InterfaceAbstract class FieldsOnly static public constants public static final int ZERO = 0; Constants and instance variable data MethodsNo implementation allowed (no abstract modifier necessary) Abstract or concrete InheritanceA subclass can implement many interfacesA subclass can inherit extend only one class Can extend numerous interfacesCan implement numerous interfaces Cannot extend a classExtends one class RootnoneObject (of all classes) namesAdjective or NounsNouns


Download ppt "AP Computer Science TOPICS TO DISCUSS.equals() == instanceof operator compareTo Interfaces Abstract Classes."

Similar presentations


Ads by Google