CSE 1030: Implementing Mixing static and non-static features Mark Shtern
Summary Class this parameter Memory Standard methods compareTo toString, equals, hashCode compareTo
Ex10 Design and implement a Rectangle class Attributes Width Height Methods getArea Assessors, Mutators Write application that sorts Rectangles by area
Find a Bug import java.util.*; public class Name { private final String first, last; public Name(String first, String last) { this.first = first; this.last = last; } public boolean equals(Object o) { if (!(o instanceof Name)) return false; Name n = (Name)o; return n.first.equals(first) && n.last.equals(last); public static void main(String[] args) { Set<Name> s = new HashSet<Name>(); s.add(new Name("Mickey", "Mouse")); System.out.println (s.contains(new Name("Mickey", "Mouse"))); }
Avoiding code duplication Constructor Chaining Delegation to Mutators Delegation to Accessors
Attribute Attribute selection Attribute Caching Money Cents Polynomial Coefficients Attribute Caching
Summary Objects Utility Class
Utility vs Class State full static this Constructors Methods State less
Utility vs Class Utility Object/Class State less or shared state static No public constructors All static methods Invocation: ClassName.methodName() Object/Class State Public constructors Instance variables/ Attributes Instance Reference variable/this Invocation: objectName.methodName() Instantiation: obj Name= new ClassName(...)
Standard Methods (Object) toString() returns a string that represents the current object equals() indicates whether some other object is "equal to" this one hashCode() returns an integer (hash code value) for the object. This method is supported for the benefit of containers
V Hash Code Examples Object Hash Code Point p1 = new Point(); 1 12 Object Hash Code Point p1 = new Point(); 1 Point p2 = new Point(); V
V V Hash Code Examples Object Hash Code Point p1 = new Point(1,2); 1 12 V Object Hash Code Point p1 = new Point(1,2); 1 Point p2 = new Point(1,1); V
Immutable Objects It is an object whose state cannot be modified after it is created. String, Double, Integer No public mutators
Features Static Feature Non-static Feature Mixing Static and Non-Static Feature
Incorporating an Invocation Counter Refractor the Rectangle class to keep track of the number of times the getArea method is used
Stamping a Serial Number on Objects Design a patter that helps to associate unique serial number with every instance of a class Apply the pattern for Rectangle class. Every rectangle should have a unique serial number that starts at 1 and increments serially.
Singleton Pattern Singleton pattern is restricting the instantiation of a class to one object Singleton pattern is a design pattern public static ClassName getInstance(); private static ClassName instance = new ClassName(..);