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

Slides:



Advertisements
Similar presentations
 Specifies a set of methods (i.e., method headings) that any class that implements that interface must have.  An interface is a type (but is not a class).
Advertisements

Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Java Programming Abstract classes and Interfaces.
INHERITANCE BASICS Reusability is achieved by INHERITANCE
INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
Strings Testing for equality with strings.
MSc IT Programming Methodology (2). number name number.
Logic & program control part 2: Simple selection structures.
IntroductionIntroduction  Computer program: an ordered sequence of statements whose objective is to accomplish a task.  Programming: process of planning.
Lecture 17 Abstract classes Interfaces The Comparable interface Event listeners All in chapter 10: please read it.
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
1 interfaces Professor Evan Korth. review Based on the GeometricObject -> Circle -> Cylinder hierarchy from last class, which of these are legal? GeometricObject.
CS 106 Introduction to Computer Science I 11 / 20 / 2006 Instructor: Michael Eckmann.
Chapter 10 Classes Continued
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Polymorphism & Interfaces
1 Identifiers  Identifiers are the words a programmer uses in a program  An identifier can be made up of letters, digits, the underscore character (
***** SWTJC STEM ***** Chapter 2-2 cg Identifiers - Naming Identifier, the name of a Java programming component. Identifier naming rules... Must.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
String Class in Java java.lang Class String java.lang.Object java.lang.String java.lang.Object We do not have to import the String class since it comes.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
The Java Programming Language
CS 106 Introduction to Computer Science I 04 / 20 / 2007 Instructor: Michael Eckmann.
Recitation 4 Abstract classes, Interfaces. A Little More Geometry! Abstract Classes Shape x ____ y ____ Triangle area() base____ height ____ Circle area()
C Derived Languages C is the base upon which many build C++ conventions also influence others *SmallTalk is where most OOP comes Java and Javascript have.
Chapter 2: Java Fundamentals
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
1 Object Oriented Design and UML Class Relationships –Dependency –Aggregation –Interfaces –Inheritance Interfaces Reading for this Lecture: L&L 6.4 – 6.5.
Chapter 6 Object-Oriented Design. © 2004 Pearson Addison-Wesley. All rights reserved6-2 Object-Oriented Design Now we can extend our discussion of the.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
1 Enhanced Class Design -- Introduction  We now examine several features of class design and organization  that can improve reusability and system elegance.
Some Standard Classes Goals The Object class The String class Wrapper classes The Math class Random Numbers.
Vladimir Misic: Characters and Strings1Tuesday, 9:39 AM Characters and Strings.
Java Language Basics By Keywords Keywords of Java are given below – abstract continue for new switch assert *** default goto * package.
Coding Bat: Ends in ly Given a string of even length, return a string made of the middle two chars, so the string "string" yields "ri". The string.
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced.
Chapter 6 Object-Oriented Design Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/20 The this Reference The this reference allows an object.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Side effects A side effect is anything that happens in a method other than computing and/or returning a value. Example: public class hello { public int.
Objects and Classes Start on Slide 30 for day 2 Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Much of.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Working with Java.
Software Development Java Classes and Methods
Interfaces Professor Evan Korth.
Wrapper Classes ints, doubles, and chars are known as primitive types, or built-in types. There are no methods associated with these types of variables.
Primitive Types Vs. Reference Types, Strings, Enumerations
CS 302 Week 11 Jim Williams, PhD.
Data Types, Identifiers, and Expressions
null, true, and false are also reserved.
Introduction to Java Programming
An overview of Java, Data types and variables
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
CSE 1030: Implementing GUI Mark Shtern.
Can perform actions and provide communication
Chapter 8 Class Inheritance and Interfaces
2009 Test Key.
Object-Oriented Design Part 2
INTERFACES Explained By: Sarbjit Kaur. Lecturer, Department of Computer Application, PGG.C.G., Sector: 42, Chandigarh.
Presentation transcript:

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

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.

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

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

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

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.

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

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

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

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

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

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

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

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

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 #

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

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)

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

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

Returning 1, -1 or 0

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

whatObject(SuperHero h)

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.

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.

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.

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

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)

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.

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

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

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.

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.

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

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

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!

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