IIT CS 201 - Object-Oriented Programming Part 2: User-Defined Classes

Unformatted text preview:

1Chapter 7Object-Oriented Programming Part 2: User-Defined ClassesHOMETopics• Defining a Class• Defining Instance Variables• Writing Methods• The Object Reference this• The toString and equals Methods• static Members of a Class• Graphical Objects • enum Types• Creating Packages• Documentation Using Javadoc HOMEWhy User-Defined Classes?Primitive data types (int, double, char, .. ) are great …… but in the real world, we deal with more complex objects: products, Web sites, flight records, employees, students, ..Object-oriented programming enables us to manipulate real-world objects.HOMEUser-Defined Classes• Combine data and the methods that operate on the data • Advantages:– Class is responsible for the validity of the data.– Implementation details can be hidden.– Class can be reused.• Client of a class– A program that instantiates objects and calls methods of the class2HOMESyntax for Defining a ClassaccessModifier class ClassName{// class definition goes here}• 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 packageHOMESoftware Engineering Tip • Use a noun for the class name. • Begin the class name with a capital letter.HOMEImportant Terminology• Fields– instance variables: data for each object– class data: static data that all objects share• Members– fields and methods• Access Modifier– determines access rights for the class and its members– defines where the class and its members can be usedHOMEAccess Modifiersmethods in the same package only No access modifier (package access)methods of the same class, methods of subclasses, and methods of classes in the same packageprotectedmethods of the same class onlyprivatemethods of the same class, and methods of other classespublicClass or members can be referenced by…Access Modifier3HOMEpublicvs. private• Classes are usually declared to be public• Instance variables are usually declared to be private• Methods that will be called by the client of the class are usually declared to be public• Methods that will be called only by other methods of the same class are usually declared to be private• APIs of methods are published (made known) so that clients will know how to instantiate objects and call the methods of the classHOMEDefining Instance VariablesSyntax: accessModifier dataType identifierList;dataType can be primitive date type or a class typeidentifierList can contain:– one or more variable names of the same data type– multiple variable names separated by commas– initial values• Optionally, instance variables can be declared as finalHOMEExamples of Instance Variable Definitionsprivate String name = "";private final int PERFECT_SCORE = 100,PASSING_SCORE = 60;private int startX, startY, width, height;HOMESoftware Engineering Tips • Define instance variables for the data that all objects will have in common.• Define instance variables as private so that only the methods of the class will be able to set or change their values.• Begin the identifier name with a lowercase letter and capitalize internal words.4HOMEThe Auto Classpublic class Auto{private String model;private int milesDriven;private double gallonsOfGas; }HOMEWriting MethodsSyntax:accessModifier returnType methodName( parameter list ) // method header{ // method body}• 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.HOMESoftware Engineering Tips• Use verbs for method names.• Begin the method name with a lowercase letter and capitalize internal words.HOMEMethod Return Types• The return type of a method is the data type of the value that the method returns to the caller. 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.5HOMEMethod Body• The code that performs the method's function is written between the beginning and ending curly braces {…}.• Unlike if statements and loops, these curly braces are required, regardless of the number of statements in the method body. • In the method body, a method can declare variables, call other methods, and use any of the program structures we've discussed, such as if/else statements, while loops, for loops, switchstatements, and do/while loops.HOMEmain is a Methodpublic static void main( String [] args ){// application code}Let's look at main's API in detail:publicmain can be called from outside theclass. (The JVM calls main.)staticmain can be called by the JVMwithout instantiating an object.voidmain does not return a valueString [] argsmain's parameter is a String arrayHOMEValue-Returning Methods• Use a return statement to return the value• Syntax:return expression;HOMEConstructors• Special methods that are called when an object is instantiated using the new keyword. • A class can have several constructors. • The job of the class constructors is to initialize the instance variables of the new object.6HOMEDefining a ConstructorSyntax:public ClassName( parameter list ) {// constructor body }Note: no return value, not even void!• Each constructor must have a different number of parameters or parameters of different types• Default constructor: a constructor that takes no arguments.• See Examples 7.1 and 7.2, Auto.java and AutoClient.javaHOMEDefault Initial Values• If the constructor does not assign values to the instance variables, they are auto-assigned default values depending on the instance variable data type.nullAny object reference (for example, a String)falsebooleanspacechar0.0float, double 0byte, short, int, longDefault ValueData TypeHOMECommon ErrorTrap Do not specify a return value for a constructor (not even void). Doing so will cause a compiler error in the client program when the client attempts to instantiate an object of the class.HOMEClass Scope• Instance variables have class scope– Any constructor or method of a class can directly refer to instance variables.• Methods also have class scope– Any method or constructor of a class can call any other method of a class (without using an object reference).7HOMELocal Scope• A method's parameters have local scope, meaning that: – a method can directly access its parameters.– a


View Full Document

IIT CS 201 - Object-Oriented Programming Part 2: User-Defined Classes

Download Object-Oriented Programming Part 2: User-Defined Classes
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Object-Oriented Programming Part 2: User-Defined Classes and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Object-Oriented Programming Part 2: User-Defined Classes 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?