Topics • Defining a Class • Defining Instance Variables • Writing Methods Chapter 7 • The Object Reference this • The toString and equals Methods Object-Oriented Programming • static Members of a Class Part 2: • Graphical Objects User-Defined Classes • enum Types • Creating Packages • Documentation Using Javadoc HOME Why User-Defined Classes? User-Defined Classes Primitive data types ( int , double , char , .. ) are • Combine data and the methods that operate on the great … data • Advantages: … but in the real world, we deal with more – Class is responsible for the validity of the data. complex objects: products, Web sites, flight – Implementation details can be hidden. records, employees, students, .. – Class can be reused. Object-oriented programming enables us to • Client of a class manipulate real-world objects. – A program that instantiates objects and calls methods of the class HOME HOME 1
Software Engineering Syntax for Defining a Class Tip accessModifier class ClassName { • Use a noun for the class name. // class definition goes here } • Begin the class name with a capital letter. • Class or members can be referenced by – methods of the same class, – methods of other classes – methods of subclasses, – methods of classes in the same package HOME HOME Access Modifiers Important Terminology • Fields Access Modifier Class or members can be referenced by… – instance variables : data for each object public methods of the same class, and – class data : static data that all objects share methods of other classes • Members private methods of the same class only – fields and methods protected methods of the same class, methods • Access Modifier of subclasses, and methods of – determines access rights for the class and its classes in the same package members No access modifier methods in the same package only – defines where the class and its members can be ( package access) used HOME HOME 2
public vs. private Defining Instance Variables Syntax: • Classes are usually declared to be public • Instance variables are usually declared to be private accessModifier dataType identifierList; • Methods that will be called by the client of the class are usually declared to be public dataType can be primitive date type or a class type • Methods that will be called only by other methods of the identifierList can contain: same class are usually declared to be private – one or more variable names of the same data type – multiple variable names separated by commas • APIs of methods are published (made known) so that – initial values clients will know how to instantiate objects and call the • Optionally, instance variables can be declared as methods of the class final HOME HOME Examples of Instance Variable Software Engineering Definitions Tips private String name = ""; • Define instance variables for the data that all objects will have in common. private final int PERFECT_SCORE = 100, • Define instance variables as private so that only PASSING_SCORE = 60; the methods of the class will be able to set or change their values. private int startX, startY, • Begin the identifier name with a lowercase letter width, height; and capitalize internal words. HOME HOME 3
The Auto Class Writing Methods Syntax: public class Auto accessModifier returnType methodName( parameter list ) // method header { { private String model; // method body private int milesDriven; } private double gallonsOfGas; • parameter list is a comma-separated list of data } types and variable names. – To the client, these are arguments – To the method, these are parameters • Note that the method header is the method API. HOME HOME Software Engineering Method Return Types Tips • Use verbs for method names. • The return type of a method is the data type of • Begin the method name with a lowercase letter the value that the method returns to the caller. and capitalize internal words. The return type can be any of Java's primitive data types, any class type, or void . • Methods with a return type of void do not return a value to the caller. HOME HOME 4
Method Body main is a Method • The code that performs the method's function is public static void main( String [] args ) written between the beginning and ending curly { braces {…}. // application code • Unlike if statements and loops, these curly braces } are required, regardless of the number of Let's look at main' s API in detail: statements in the method body. main can be called from outside the public • In the method body, a method can declare class. (The JVM calls main. ) variables, call other methods, and use any of the main can be called by the JVM static program structures we've discussed, such as without instantiating an object. if/else statements, while loops, for loops, switch main does not return a value void statements, and do/while loops. String [] args main 's parameter is a String array HOME HOME Value-Returning Methods Constructors • Use a return statement to return the value • Special methods that are called when an object is instantiated using the new keyword. • Syntax: return expression; • A class can have several constructors. • The job of the class constructors is to initialize the instance variables of the new object. HOME HOME 5
Defining a Constructor Default Initial Values • If the constructor does not assign values to the Syntax: instance variables, they are auto-assigned default public ClassName( parameter list ) values depending on the instance variable data { // constructor body type. } Data Type Default Value Note: no return value, not even void ! 0 byte, short, int, long • Each constructor must have a different number of float, double 0.0 parameters or parameters of different types • Default constructor : a constructor that takes no char space arguments. boolean false • See Examples 7.1 and 7.2, Auto.java and AutoClient.java Any object reference (for null example, a String ) HOME HOME Common Error Class Scope Trap • Instance variables have class scope Do not specify a return value for a constructor (not – Any constructor or method of a class can even void ). directly refer to instance variables. • Methods also have class scope Doing so will cause a compiler error in the client – Any method or constructor of a class can call program when the client attempts to instantiate any other method of a class (without using an an object of the class. object reference). HOME HOME 6
Local Scope Summary of Scope • A method's parameters have local scope , meaning • A method in a class can access: that: – the instance variables of its class – a method can directly access its parameters. – any parameters sent to the method – a method's parameters cannot be accessed by – any variable the method declares from the point other methods. of declaration until the end of the method or • A method can define local variables which also until the end of the block in which the variable have local scope, meaning that: is declared, whichever comes first – a method can access its local variables. – any methods in the class – a method's local variables cannot be accessed by other methods. HOME HOME Accessor Methods Accessor Methods • Clients cannot directly access private instance • Example: the accessor method for model . variables, so classes provide public accessor methods with this standard form: public String getModel( ) public returnType getInstanceVariable( ) { { return instanceVariable; return model; } } (returnType is the same data type as the instance • See Examples 7.3 Auto.java & 7.4 AutoClient.java variable) HOME HOME 7
Mutator Methods Mutator Methods • Allow client to change the values of instance • Example: the mutator method for milesDriven variables public void setMilesDriven( int newMilesDriven ) { if ( newMilesDriven >= 0 ) public void setInstanceVariable( milesDriven = newMilesDriven; dataType newValue ) else { { // validate newValue, System.err.println( "Miles driven " // then assign to instance variable + "cannot be negative." ); } System.err.println( "Value not changed." ); } } • See Examples 7.5 Auto.java & 7.6 AutoClient.java HOME HOME Common Error Software Engineering Trap Tip • Do not declare method parameters. – Parameters are defined already and are assigned • Write the validation code for the instance variable the values sent by the client to the method. in the mutator method and have the constructor • Do not give the parameter the same name as the call the mutator method to validate and set initial instance variable. values – The parameter has name precedence so it • This eliminates duplicate code and makes the " hides " the instance variable. program easier to maintain • Do not declare a local variable with the same name as the instance variable. – Local variables have name precedence and hide the instance variable. HOME HOME 8
Recommend
More recommend