Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

User-Defined Classes in Object-Oriented Programming, Study notes of Computer Science

An overview of user-defined classes in object-oriented programming. It covers the syntax for defining a class, access modifiers, instance variables, methods, and accessor and mutator methods. The document also discusses the advantages of using user-defined classes and provides software engineering tips.

Typology: Study notes

Pre 2010

Uploaded on 08/18/2009

koofers-user-8jy-1
koofers-user-8jy-1 🇺🇸

10 documents

1 / 16

Toggle sidebar

Related documents


Partial preview of the text

Download User-Defined Classes in Object-Oriented Programming and more Study notes Computer Science in PDF only on Docsity! 1 Chapter 7 Object-Oriented Programming Part 2: User-Defined Classes HOME Topics • 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 HOME Why 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. HOME User-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 class 2 HOME Syntax for Defining a Class accessModifier 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 package HOME Software Engineering Tip • Use a noun for the class name. • Begin the class name with a capital letter. HOME Important 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 used HOME Access Modifiers methods 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 package protected methods of the same class onlyprivate methods of the same class, and methods of other classes public Class or members can be referenced by… Access Modifier 5 HOME Method 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, switch statements, and do/while loops. HOME main is a Method public static void main( String [] args ) { // application code } Let's look at main's API in detail: public main can be called from outside the class. (The JVM calls main.) static main can be called by the JVM without instantiating an object. void main does not return a value String [] args main's parameter is a String array HOME Value-Returning Methods • Use a return statement to return the value • Syntax: return expression; HOME Constructors • 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. 6 HOME Defining a Constructor Syntax: 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.java HOME Default 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) falseboolean spacechar 0.0float, double 0byte, short, int, long Default ValueData Type HOME Common Error Trap 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. HOME Class 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). 7 HOME Local Scope • A method's parameters have local scope, meaning that: – a method can directly access its parameters. – a method's parameters cannot be accessed by other methods. • A method can define local variables which also have local scope, meaning that: – a method can access its local variables. – a method's local variables cannot be accessed by other methods. HOME Summary of Scope • A method in a class can access: – the instance variables of its class – any parameters sent to the method – any variable the method declares from the point of declaration until the end of the method or until the end of the block in which the variable is declared, whichever comes first – any methods in the class HOME Accessor Methods • Clients cannot directly access private instance variables, so classes provide public accessor methods with this standard form: public returnType getInstanceVariable( ) { return instanceVariable; } (returnType is the same data type as the instance variable) HOME Accessor Methods • Example: the accessor method for model. public String getModel( ) { return model; } • See Examples 7.3 Auto.java & 7.4 AutoClient.java 10 HOME The toString API toString( ) returns a String representing the data of an object String Method name and argument listReturn value HOME Auto Class toString Method public String toString( ) { DecimalFormat gallonsFormat = new DecimalFormat( "#0.0" ); return "Model: " + model + "; miles driven: " + milesDriven + "; gallons of gas: " + gallonsFormat.format( gallonsOfGas ); } HOME The equals Method • Determines if the data in another object is equal to the data in this object • Example client code using Auto references auto1 and auto2: if ( auto1.equals( auto2 ) ) System.out.println( "auto1 equals auto2" ); equals( Object obj ) returns true if the data in the Object obj is the same as in this object; false otherwise. boolean Method name and argument listReturn value HOME Auto Class equals Method public boolean equals( Auto autoA ) { if ( model.equals( autoA.model ) && milesDriven == autoA.milesDriven && Math.abs( gallonsOfGas - autoA.gallonsOfGas ) < 0.0001 ) return true; else return false; } • See Examples 7.10 Auto.java & 7.11 AutoClient.java 11 HOME static Variables • Also called class variables • One copy of a static variable is created per class • static variables are not associated with an object • static constants are often declared as public • To define a static variable, include the keyword static in its definition: • Syntax: accessSpecifier static dataType variableName; • Example: public static int countAutos = 0; HOME static Methods • Also called class methods • Often defined to access and change static variables • static methods cannot access instance variables: – static methods are associated with the class, not with any object. – static methods can be called before any object is instantiated, so it is possible that there will be no instance variables to access. HOME Rules for static and Non-static Methods • See Examples 7.12 and 7.13 yesnoUse the object reference this? yesnoCall non-static instance methods? yesyesCall static class methods? yesyesAccess static class variables? yesnoAccess instance variables? Non-static Method static Method HOME Reusable Graphical Objects • In Chapter 4, the applet code and the Astronaut were tightly coupled; we couldn't draw the Astronaut without running the applet. • To separate the Astronaut from the applet, we can define an Astronaut class. – The starting x and y values become instance variables, along with a new scaling factor. – We move the code for drawing the Astronaut into a draw method. • The applet instantiates an Astronaut object in init and calls draw from the paint method. • See Examples 7.14, 7.15, and 7.16. 12 HOME enum Types • Special class definition designed to increase the readability of code • Allows you to define a set of objects that apply names to ordered sets • Examples of ordered sets: – Days of the week – Months of the year – Playing cards HOME enum • Built into java.lang (no import statement needed) • Syntax: enum EnumName { obj1, obj2,… objn }; • Example enum Days { Sun, Mon, Tue, Wed, Thurs, Fri, Sat }; • When this statement is executed A constant object is instantiated for each name in the list. Thus, each name is a reference to an object of type Days HOME Using an enum Object • Referring to an enum object reference – Syntax: EnumType.enumObject – Example: Days.Mon • Declaring an object reference of an enum type – Syntax: EnumType referenceName – Example: Days d; // d is null initially d = Days.Thurs; HOME Useful enum Methods ordinal( ) returns the numeric value of the enum object. By default, the value of the first object in the list is 0, the value of the second object is 1, and so on. int compareTo( Enum eObj ) compares two enum objects and returns a negative number if this object is less than the argument, a positive number if this object is greater than the argument, and 0 if the two objects are the same. int Method name and argument listReturn value 15 HOME Javadoc Documentation • The Java class library documentation on Sun's Web site (www.java.sun.com) helps us learn how to instantiate objects and call methods for the classes. • This documentation was generated using Javadoc, a tool provided in the Java Software Development Toolkit (SDK). • We can also use Javadoc to generate Web pages that provide documentation on our class's fields and methods. HOME To Use Javadoc • We need to add Javadoc comments and special tags to our classes. • Javadoc comments begin with /** and end with */ (Note that this is similar to a Java block comment, but with an extra * in the opening syntax.) • Example: /** Auto class * Anderson, Franceschi */ HOME Block Tags • Identify parameters and return values • HTML tags can be used in the descriptions – For example, <BR> to insert a new line @return description@return @param variableName description@param Common syntaxTag HOME Sample equals Method Documentation /** * equals method:<BR> * Compares the fields of two Auto objects * @param a1 another Auto object * @return a boolean, true if this object * has the same field values as the parameter a1 */ public boolean equals( Auto a1 ) { return ( model.equals( a1.model ) && milesDriven == a1.milesDriven && Math.abs( gallonsOfGas - a1.gallonsOfGas ) < 0.001 ); } 16 HOME Executing Javadoc • javadoc.exe is located in the bin directory of the Java SDK • To generate documentation for a class: javadoc Class.java Example: javadoc Auto.java • To generate documentation for all classes in a directory: javadoc *.java • See Example 7.22 HOME Sample Javadoc Documentation
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved