Instance Methods


Instance Methods

There are two basic types of methods ”instance and static. An instance method is associated with an object. Instance is the default type for methods. Every object will share the same implementation of the method, but the method will act upon the data specific to its associated object. As a matter or semantics, objects do not call instance methods. Instance methods are called on objects.

Inside the class in which it is defined, an instance method can be called by simply typing the method name and providing the appropriate number of arguments. Outside of the class in which it is defined, an instance method can only be called by referencing an instance of the class. The syntax for calling an instance method outside of its class is the instance variable name, a period, the method name , and any input arguments.

 instance_name.method_name(arguments); 

Example: Writing Instance Methods

This example shows a typical use of instance methods ”to retrieve or change the value of a data member. The InstanceDemo class declares one instance variable named pressure . We do not want to allow direct access to the variable outside of the InstanceDemo class so the variable is given private access. The InstanceDemo class provides access to the pressure variable through two methods ” getPressure() returns the current value of the variable, setPressure() changes the value of the variable. The names get and set are the conventional beginnings for names of data member access methods.

 public class InstanceDemo {   private double pressure;   //  The InstanceDemo constructor initializes the   //  pressure field.   public InstanceDemo(double p) {     pressure = p;   }   //  Define methods to access or change   //  the value of the pressure variable   public double getPressure() {     return pressure;   }   public void setPressure(double p) {     pressure = p;   }   public static void main(String args[]) {     InstanceDemo demo = new InstanceDemo(21.95);     //  Call two methods of the InstanceDemo class     demo.setPressure(54.3);     System.out.println("pressure is " +                           demo.getPressure());   } } 

Output ”

 pressure is 54.3 


Technical Java. Applications for Science and Engineering
Technical Java: Applications for Science and Engineering
ISBN: 0131018159
EAN: 2147483647
Year: 2003
Pages: 281
Authors: Grant Palmer

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