Section 10.7. Concepts Summary


[Page 339 (continued)]

10.7. Concepts Summary

In this chapter we introduced class methods, private methods, and building methods from other methods.

10.7.1. Class Methods

Class methods are general methods like Math.abs(int num) or methods that create objects like Sound.createTriangleWave(int freq, int maxAmplitude). Class methods do not work on object data! There is no implicit current object passed to a class method so you can't use the keyword this.

Class methods are defined with the keyword static on the method declaration: visibility static returnType methodName(parameterList).

public static Sound createTriangleWave(int freq, int maxAmplitude)


You can invoke a class method using ClassName.methodName(parameterList). To invoke the class method createTriangleWave on the class Sound and then save a reference to the new Sound object in a variable called triangle do the following:

> Sound triangle = Sound.createTriangleWave(440,4000);


If the method doesn't use object data, then it can be a class method. If a method does use object data, then it should be an object method.

10.7.2. Private Methods

Private methods can only be invoked from code in the same class that they are declared in. Use private methods to break down long public methods into smaller reusable parts.


[Page 340]

To declare a method to be private use the private keyword for the visibility. Remember that to declare a method you can use visibility [static] returnType method-Name(parameterList). The static keyword is optional and is used for declaring class methods.

private void playJingleBellsRefrain()


If you try to access a private method from code outside the class the method is defined in, you will get an error.

> MidiPlayer player = new MidiPlayer(); > player.playJingleBellsRefrain(); java.lang.IllegalAccessException: Class koala.dynamicjava.interpreter.EvaluationVisitor can not access a member of class MidiPlayer with modifiers "private"   at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:57)   at java.lang.reflect.Method.invoke(Method.java:317)


10.7.3. Build a Program from Multiple Methods

You can build a program (method) from several methods. If you want to play a whole song like Jingle Bells, you can break it into smaller reusable methods.

/*  * Method to play Jingle Bells  */ public void playJingleBells() {   // play verse 1   playJingleBellsV1();   // play refrain   playJingleBellsRefrain();   // play verse 2   playJingleBellsV2();   // play refrain   playJingleBellsRefrain(); }


Long methods are hard to read and understand. Try to break down methods into smaller parts.



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