AP Computer Science

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

description

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

Transcript of AP Computer Science

Page 1: AP Computer Science

AP Computer Science

TOPICS TO DISCUSS

.equals() ==instanceof operator compareToInterfacesAbstract Classes

Page 2: AP Computer Science

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.

Page 3: AP Computer Science

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”) 10-3

Sun

Page 4: AP Computer Science

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.

10-4

s referenceSun

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

Page 5: AP Computer Science

10-5

String s1 = "Sun";String s3 = “Sun”;

String s4 = new String(“Sun“); String s5 = new String (“Sun”);

s1

s4

s5"Sun"

String reference

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

Page 6: AP Computer Science

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.

Page 7: AP Computer Science

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

Page 8: AP Computer Science

Why does this matter?

String comparison:

There are three ways to compare String objects:

1. By equals() method (inherited from Object) 2. By == operator3. By compareTo() method

10-8

Page 9: AP Computer Science

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

Page 10: AP Computer Science

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); trueboolean b = n.equalsIgnoreCase(v); true

10-10

Page 11: AP Computer Science

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

String reference

“Computer"

HEAP

Page 12: AP Computer Science

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

Page 13: AP Computer Science

compareTo method parameters

10-13

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 < than the string return > 0 (positive

number) .

Page 14: AP Computer Science

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

10-14

http://ss64.com/ascii.html

Page 15: AP Computer Science

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 65Apple lowercase a is 96

Is Apple > apple no65 – 97 = - 32Prints negative #

Page 16: AP Computer Science

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

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 < than the string return > 0 (positive number 10-16

65 - 97

97 - 65

97 - 97

Page 17: AP Computer Science

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

10-17

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)

-32 32 5 0

Page 18: AP Computer Science

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 # = positiveSuperHero ironman = new SuperHero(“IronMan”, “Toys”, “Suit”);

SuperHero captainAmerica = new CaptainAmerica(“Captain America”, “Shield”, “Strength”, 10);

SuperHero captainAmerica2 = new CaptainAmericaCaptain America”, “Shield”, “Strength”, 15);

Page 19: AP Computer Science

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

Page 20: AP Computer Science

Returning 1, -1 or 0

Page 21: AP Computer Science

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

Page 22: AP Computer Science

whatObject(SuperHero h)

Page 23: AP Computer Science

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.

Page 24: AP Computer Science

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.

Page 25: AP Computer Science

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.

Page 26: AP Computer Science

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).

Page 27: AP Computer Science

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 implementsYou must implement all the methods from the interface. It created code (body) for the fly method. (It implemented the fly method)

Page 28: AP Computer Science

Class that implements Flierpublic class Bird implements Flier{ public void fly( ) // public must be written here{System.out.println("Using my wings to fly");

}}

Bird implements FlierIt created code for the method fly (It implemented the method)

It does something different from Airplane.

Page 29: AP Computer Science

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

Page 30: AP Computer Science

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();

Page 31: AP Computer Science

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.

Page 32: AP Computer Science

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.

Page 33: AP Computer Science

Class that extends Shapepublic 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

Page 34: AP Computer Science

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

Page 35: AP Computer Science

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!

Page 36: AP Computer Science

Interface vs. abstract class (cont)Interface Abstract class

Fields Only static public constantspublic static final int ZERO = 0;

Constants and instance variable data

Methods No implementationallowed (no abstract modifier necessary)

Abstract or concrete

Inheritance A subclass can implement many interfaces A subclass can inherit extend only one class

Can extend numerous interfaces Can implement numerous interfaces

Cannot extend a class Extends one class

Root none Object (of all classes)

names Adjective or Nouns Nouns