CSC152 2005F, Class 24: Review of Static Aspects of Classes Admin: * Questions Overview: * Classes, continued Classes, Continued * Five parts to template classes * Fields, * Constructors, * Methods, * Class Fields (also called "Static Fields") * Class Methods (also called "Static Methods") * Static fields and methods are associated with the class as a whole. * Need not create an object to use them. * Objects "share" these fields. * Terminology: If we don't say "static" or "class", we mean "associated with objects". We can also explicitly say "Object Method" and "Object Field" * Outside of the class, refer to static methods wtih CLASSNAME.methodName() * Inside the class, refer to static fields fieldName * Some static methods provide alternatives to constructors. * Some such static methods "parse" a parameter to construct a value. e.g., public static Fraction parseFraction(String name) { int slash = name.indexOf("/"); String num = name.subString(0,slash); String denom = name.subString(slash+1); return new Fraction(Integer.parseInt(num), Integer.parseInt(denom)); } vs. public Fraction(String name) { int slash = name.indexOf("/"); String num = name.subString(0,slash); String denom = name.subString(slash+1); this.numerator = Integer.parseInt(num); this.denominator = Integer.parseInt(denom); } * Why write a static method rather than a constructor to "construct" (e.g., why write static parseFraction rather than Fraction(String)) * Seems clearer to some people. ("it feels right") * Deals with ambiguous parameters to the constructor public Vec2D(double x, double y) public Vec2D(double radius, double theta) // Create a new two-dimenstional vector with xcoord a and y coord b // Create a new two-dimensional vector with radius a and angle b One of these two will need to be a static method rather than a constructor new Vec2D(1.0, 3.0); * You don't always construct new objects; sometimes you reuse existing ones. * E.g., instead of public Tutor(Course c) ... public static Tutor getTutor(Course c) { If I already created a tutor for that course, return that tutor Otherwise Create and return a new tutor } + Best of non-mutable objects. DETOUR: * Java permits something called "overloading" * You can have multiple methods with the same name but different parameters * Different can mean "different number" * Different can also mean "different types" * AS LONG AS JAVA CAN FIGURE OUT WHICH YOU MEAN IN A CALL, YOU SHOULD BE FINE * Java has interesting policies for coercsion Assignment: Create a "MutableInteger" class The class should permit * Constructor that takes an int parameter * int intValue() * void increment(int amount) * void decrement(int amount) * MutableInteger multiply(MutableInteger other) * MutableInteger add(MutableInteger other) * static MutableInteger parseInt(String description) MutableInteger i = MutableInteger.parseInt("235"); You may use Integer.parseInt to help