Objects and Classes Lakshmish Ramaswamy Basic Methods Constructors
Objects and Classes Lakshmish Ramaswamy
Basic Methods • • Constructors Mutators and Accessors The equals method The to. String method
Basic Methods • Constructors – Object creation and Initialization • Possible to define multiple constructors • Java provides default constructors – Data variables are initialized to default values – Primitive types to zero & reference types to null • Method with same name as class and no return type
Mutators and Accessors • Mutator modifies the state of the object – Changes the data variables • Accessors examine the state of an object – Does not modify the state • Special accessors and mutators operate on single data variables – get. MMM, set. MMM
The equals Method • Testing if two objects represent same value – Recall “==“ doesn’t work public boolean equals(Object rhs) • Parameter is of Object type • Two tasks – Test rhs is of same type – Test if each individual field is equal • Return true if both conditions are true
The “to. String”Method • Outputting the state of an object • to. String produces an string represeting the state of the object • Usually concatenation of the string representations of the member fields with appropriate delimiters • Example: – MM + “/” + “DD” + “/” + “YYYY” for the date object
Static Methods • Static method does not require a controlling object • Analogous to global method in non-OO languages • Called using class name instead of object name Math. random(); • Examples: main, Integer. parse. Int, Math. max, etc. • Cannot access any non-static fields
Static Fields • Variable that all instances of a class need to share • Typically a constant • Only one instance of the variable is created public static final int MAX_VALUE = 2147483647; public static final double PI = 3. 14; • Can be accessed by any object of the particular type
- Slides: 9