120 likes | 218 Views
CS1054: Lecture 11. More Sophisticated Behavior (contd..). Today’s topics. Identity vs. equality Class variables or static variables Private vs. public accessors. Side note: String equality. String input = “bye”; if(input == "bye") { tests identity ... }
E N D
CS1054: Lecture 11 More Sophisticated Behavior (contd..)
Today’s topics • Identity vs. equality • Class variables or static variables • Private vs. public accessors
Side note: String equality String input = “bye”; if(input == "bye") { tests identity ... } if(input.equals("bye")) { tests equality ... } • Strings should (almost) always be compared with.equals
Identity vs equality 1 Other (non-String) objects: :Book :Book “Lord of the Rings” “Harry Porter” book1 book2 book1 == book2 ?
Identity vs equality 2 Other (non-String) objects: :Book :Book “Harry Porter” “Harry Porter” book1 book2 book1 == book2 ?
Identity vs equality 3 Other (non-String) objects: :Book :Book “Harry Porter” “Harry Porter” book1 book2 book1 == book2 ?
Identity vs equality (Strings) String input = reader.getInput(); if(input == "bye") { ... } == tests identity :String :String == ? "bye" "bye" input (may be) false!
Identity vs equality (Strings) equals tests equality String input = reader.getInput(); if(input.equals("bye")) { ... } :String :String ? equals "bye" "bye" input true!
Class variables.. aka.. static variables • ‘static’ keyword is used to define class variables • class variables are common to the entire class • All the objects share this variable • A static variable can be accessed from any of the class instances • Besides static variables … there are static methods (later in the semester).
Constants private final int SIZE = 10; • private: access modifier, as usual • static: class variable • final: constant
Public vs private • Public attributes (fields, constructors, methods) are accessible to other classes. • Fields should not be public. • Private attributes are accessible only within the same class. • Only methods that are intended for other classes should be public.
Information hiding • Data belonging to one object is hidden from other objects. • Know what an object can do, not how it does it. • Information hiding increases the level of independence. • Independence of modules is important for large systems and maintenance.