CS/ENGRD 2110 (formerly CS 211) Fall 2009

CS/ENGRD 2110 FALL 2018 Lecture 6: Consequence of type, casting; function equals http://courses.cs.cornell.edu/cs2110 Overview references in 2 Quick look at arrays: array Casting among classes cast, object-casting rule Operator instanceof Function getClass Function equals compile-time reference rule Homework: while-loop, for-loop while ( ) { }

// syntax for (int k= 0; k < 200; k= k+1) { } // example A2 is due Sunday 3 Everyone should get 100/100 since we gave you all the test cases you need. Please look at the pinned Piazza note Assignment A2 for information that is not in the handout and answers to questions. Before Next Lecture 4 Follow the tutorial on abstract classes and interfaces, and watch <13 minutes of videos. Abstract classes and interfaces This will prepare you for Thursdays lecture. Click these

Classes we work with today 5 Cat pet1= new Cat(5); ss Animal Dog pet2= new Dog(6); classes Cat and Dog components common to animals in Animal pet1 a0 Cat pet2 a1 a0 class hierarchy: Object Animal Dog age Dog a1 5 Animal isOlder(Animal)

age 6 isOlder(Animal) Cat toString() purr() Animal Dog toString() Cat (Object partition is there but not show 6 Casting Object Casting objects Animal

7 You know about casts like: Dog (int) (5.0 / 7.5) pet1 (double) 6 double d= 5; Cat a0 null Animal // automatic cast You can also use casts with class types: pet2 a0 Cat

a0 5 Animal Animal pet1= new Cat(5); age Cat pet2= (Cat) pet1; isOlder(Animal) A class cast doesnt change the object. It just changes the perspective: how it is viewed! pet1 blinders toString() purr() Cat Explicit casts: unary prefix operators 8

Object-casting rule: At runtime, a0 an object can be cast to the Object name of any partition that occurs equals() within it and to nothing else. Animal a0 can be cast to Object, Animal, age 5 Cat. isOlder(Animal) An attempt to cast it to anything (Cat) c else causes an exception Cat (Object) c toString() (Cat) (Animal) (Cat) (Object) c purr() These casts dont take any time. The object does not change. Its a change of perception. c a0 Cat Implicit upward cast 9

Animal Animal Cat toString() purr() a1 age 6 Animal isOlder(Animal) Dog toString() pet2 a1 Cat 5 h blinders // pet1 is cast up to

class Animal and stored in h pet1 a0 age isOlder(Animal) public class Animal { /** = "this Animal is older than h" */ public boolean isOlder(Animal h) { return age > h.age; Cat}pet1= new Cat(5); Dog pet2= new Dog(6); if (pet2.isOlder(pet1)) {} h a0 a0 Dog Components used froma0h age

10 5 Animal isOlder(Animal) public class Animal { /** = "this is older than h" h blinders Cat */ toString() public boolean purr() isOlder(Animal h) { return age > h.age; } Which h.toString() OK its in class Object toString() partition gets called? h.isOlder() OK its in Animal See slide 18. partition h.purr() ILLEGAL not in Animal

h a0 partition or Object partition Animal 11 Compile-time reference rule Compile-time reference rule see (v1) 12 From a variable of type C, you can reference only methods/fields that are available in class C. Animal pet1= new Animal(5); pet1.purr(); pet1 a0 Animal a0 obviously illegal

Animal The compiler will give you an age 5 error. isOlder(Animal) Checking the legality of pet1.purr(): Since pet1 is an Animal, purr must be declared in Animal or one of its From an Animal variable, can use only methods available superclasses. in class Animal Compile-time reference rule see (v2) 13 From a variable of type C, you can reference only methods/fields that are available in class C. Animal pet1= new Cat(5); pet1.purr(); pet1 a0 Animal

a0 still illegal! The compiler still gives you an error. Checking the legality of pet1.purr(): Since pet1 is an Animal, purr must be declared in Animal or one of its From an Animal variable, can use only superclasses. in class Animal age 5 Animal isOlder(Animal) getNoise() toString() purr() Cat

methods available Why would we ever do this? 14 Why would a variable of type Animal ever not have just an Animal in it? This is one of the beautiful things about OO programming! We want to use an Animal method (seen) We want to keep a list of all our pets 1. 2. Create an array of type Animal! Animal[] v= new Animal[3]; 15

declaration of array v Create array of 3 elements Assign value of new-exp to Assign and refer v to elements as usual: v[0]= new Animal(); a= v[0].getAge(); Sometimes use horizontal picture of an array: v null a6 a6 Animal[] 0 null 1 null

2 null 0 v null 1 null 2 null Consequences of a class type 16 Animal[] v; // declaration of v v= new Animal[3]; // initialization of v v[0]= new Cat(5); // initialization of 1st elem v[2]= new Dog(6); 0 1 2 v a0 null a1 The type of v is Animal[] The type of each v[k] is Animal The type is part of the Animal objects syntax/grammar of the language.

Known at compile time. A variables type: Restricts what values it can contain. Determines which methods are legal to call on it. Compile-time reference rule, revisited 17 0 1 Animal[] v; // declaration of v v= new Animal[3]; // initialization of v a0 null v null Cat pet1= new Cat(5); // initialization of pet1 v[0]= pet1; // initialization of 1st elem v[0].purr(); // should this be allowed? pet1 a0 // will it compile? 2 null

a0 Checking the legality of v[0].purr(): Since v[0] is an Animal, purr must be declared in Animal or one ofuse its From an Animal variable, can superclasses. only methods available in class Animal age 5 Animal isOlder(Animal) v[0] blinders

toString() purr() Cat Bottom-up / Overriding rule revisited 18 0 1 2 Animal[] v= new v a0 null a1 Animal[3]; v[0]= new Cat(5); v[2]= new Dog(6); a v[0].toString();a 1 v[2].toString();0 Objec Objec Which toString()toString() t t toString() gets called?

Anima age 5 Anim age 6 l al Bottom-up / isOlder(Animal isOlder(Animal Overriding ) ) Cat Do rule says toString() g toString() function purr() toString in 19 Equals Example: Point Class 20

public class Point { public int x; public int y; public Point(int x, int y) { this.x= x; this.y= y; } } 21 How Object defines equals(x) p1 a0 public boolean equals(Object x) { return this == x; }oint p1= new Point(5,4); P p2 a0 p3 a1 a0 Point p2= p1; if (p1 == p2) {...}

true? if (p1.equals(p2)) {...} true? // 5 y 4 x 5 y 4 Point Point Point // a1 Point p3= new Point(5,4);

if (p1 == p3) {...} x Point // ng the Point class as defined in previous slide. Point Can define equals for your own class! 22 Can I define it any way I like? https://docs.oracle.com/javase/8/docs/api/ja va/lang/Object.html#equals-java.lang.Objec t- Java spec says: Reflexive Symmetric Transitive (click on the link to see what these are) How do we define equality for a Point? 23

/** return obj is a Point and obj and this have the same x and y fields */ @Override public boolean equals(Object obj) { // why Object? // how can we access the x y fields // if this is an Object? } Use operator instanceof 24 ob instanceof C true iff ob has a partition named C h instanceof Object true h instanceof Animal true h instanceof Cat true h instanceof JFrame false a0 age 5 Animal isOlder(Animal)

Cat toString() purr() h a0 Animal How do we define equality for a Point? 25 /** return obj is a Point and obj and this have the same x and y fields */ @Override public boolean equals(Object obj) { if (!(obj instanceof Point)) return false; Point p= (Point)obj; return (x == p.x && y == p.y); } Opinions about casting 26 Use of instanceof and down-casts can indicate bad design DO: DONT: if (x instanceof C1) do thing with (C1) x x.do()

else if (x instanceof C2) do thing with (C2) x where do is overridden in else if (x instanceof C3) the classes C1, C2, C3 do thing with (C3) x But how do I implement equals() ? That requires casting! Equals in Animal 27 a0 age 5 Animal equals(Object) public class Animal { private int age; /** return true iff this and obj are of the same class * and their age fields have same values */ public boolean equals(Object obj) { // how to check that objects are of the // same class??

} Use function getClass 28 h.getClass() Let Cat be the lowest partition of object h Then h.getClass() == Cat.class h.getClass() != Animal.class a0 age 5 Animal isOlder(Animal) Cat toString() purr() h a0 Animal Equals in Animal a0 age

29 5 Animal equals(Object) public class Animal { private int age; /** return true iff this and obj are of the same class * and their age fields have same values */ public boolean equals(Object obj) { if (obj == null || getClass() != obj.getClass()) return false; Animal an= (Animal) obj; return age == an.age; } // cast obj to Animal!!!! // downcast needed to reference a Equals in Cat 30

public class Animal { private int age; /** return true iff this and ob are of * same class and their age fields * have same values */ a0 age 5 Animal equals(Object) Cat likesPeople false equals(Object) public boolean equals(Object ob) {...} public class Cat extends Animal { private boolean likesPeople; /** return true iff this and ob are of same class * and age and likesPeople fields have same if (!super.equals(obj)) return false; values*/

public boolean obj) { is necessary! Cat c1= (Cat)equals(Object obj; // downcast return likesPeople == c1.likesPeople;

Recently Viewed Presentations

  • Presentación de PowerPoint - XBRL

    Presentación de PowerPoint - XBRL

    Fujitsu's XBRL Activities Makoto Koizumi ([email protected]) Fujitsu Limited 2006 May 16th Corporate introduction Fujitsu is: 3rd largest IT service provider in the world (Consolidated Sales Revenue USD 42.7 Billions (42,780M) (FY2005)) Providing Semiconductor, Platform, Middleware, Integration, Outsourcing and IT Consulting...
  • Chapter 9: Adding Windows NT and Internet Information Server ...

    Chapter 9: Adding Windows NT and Internet Information Server ...

    Turn off the Windows NT Server Service on the IIS Server to prevent users from viewing shares. ... Methods Anonymous Access and Authentication Control IP Access and Domain Name Restrictions Web Access Control Review Windows NT Server security recommendations Security...
  • MATH 685/CSI 700 Lecture Notes

    MATH 685/CSI 700 Lecture Notes

    MATH 685/ CSI 700/ OR 682 Lecture Notes Lecture 4. Least squares Method of least squares Linear least squares Data fitting Data fitting Example Example Example Existence/Uniqueness Normal Equations Orthogonality Orthogonality Orthogonal Projector Pseudoinverse Sensitivity and Conditioning Sensitivity and Conditioning...
  • LESSAC-MADSEN RESONANT VOICE THERAPY (LMRVT) - Adults &amp; Kids

    LESSAC-MADSEN RESONANT VOICE THERAPY (LMRVT) - Adults & Kids

    Space is limited. Cheque payable to "Hong Kong ENT Laser Centre Limited" Return registration form and payment to: Rm812, Central Building, 1-3 Pedder Street, Central, Hong Kong (Ref: LMRVT seminar & workshop- registration) Confirmation email will be sent out within...
  • g - St. Johns County School District

    g - St. Johns County School District

    When the price ceiling is above the equilibrium price, the equilibrium price is still perfectly legal. Just because landlords are allowed to charge $1000 rent doesn't mean they will—if they do, they won't be able to rent all of their...
  • WA Clozapine Initiation and Titration Chart Version 3,

    WA Clozapine Initiation and Titration Chart Version 3,

    Metformin Olanzapine Paracetamol Quetiapine Risperidone Sodium Valproate Temazepam Venlafaxine 69 80 46 42 26 28 29 38 73 79 91 37 46 36 28. ... CMI and explain treatment ... Aqua PowerPoint template to meet Style Guide requirements Keywords: aqua,...
  • Dear PowerPoint®* Users,

    Dear PowerPoint®* Users,

    * Opportunity Overview Potential Earnings As an Herbalife Independent Distributor, you can become eligible to earn from six areas of potential income and incentives Retail Profit Wholesale Profit Royalty Overrides Monthly Production Bonus Annual Bonus (Mark Hughes Bonus) Promotions The...
  • Welcome to Psychology - Weebly

    Welcome to Psychology - Weebly

    Before we begin… Fold the piece of paper in three to create a name card. Write your name/preferred name on the front. Make sure it is clear and bold so I can see it!