Section 3.7. Concepts Summary


[Page 69 (continued)]

3.7. Concepts Summary

This chapter introduced many concepts: invoking object and class methods, creating objects, and how to create new methods.

3.7.1. Invoking Object Methods

You must invoke an object method on an object.

objectReference.methodName(parameterList);


Here is an example of invoking an object method:

> turtle1.turnLeft();


The object that the method is invoked on will be implicitly passed to the method and can be referred to using the keyword this inside of the method. Object methods usually work with the data in the current object.

3.7.2. Invoking Class Methods

You can invoke a class method using the name of the class.

ClassName.methodName(parameterList);


Here is an example of invoking a class method:

> System.out.println(Math.abs(-3)); 3


Class methods are used for general methods like absolute value. Class methods do not have access to object data.

3.7.3. Creating Objects

To create an object, ask the class to create and initialize a new object. This is also called creating an instance of a class or instantiating an object.

new ClassName(parameterList)


Here is an example of creating an object of the class World:

> World worldObj = new World();


3.7.4. Creating New Methods

To create a method in a class, open the class definition file ClassName.java, and put the method before the closing curly brace at the end of the file.


[Page 70]

To define a method use:

public returnType methodName(parameterList) {   // statements in the body of the method }


If the method doesn't return a value, use the keyword "void" as the return type. Each parameter in the parameter list has a type and name. Parameters are separated by commas. Method and parameter names start with a lowercase letter, but the first letter of each additional word is capitalized.

Here is an example method in the Turtle class:

/**  * Method to draw a square with a width and height  * of 30  */ public void drawSquare() {   this.turnRight();   this.forward(30);   this.turnRight();   this.forward(30);   this.turnRight();   this.forward(30);   this.turnRight();   this.forward(30); }




Introduction to Computing & Programming Algebra in Java(c) A Multimedia Approach
Introduction to Computing & Programming Algebra in Java(c) A Multimedia Approach
ISBN: N/A
EAN: N/A
Year: 2007
Pages: 191

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net