Accessing Methods


The following script creates a Car object named myCar, calls the fullThrottle method via the myCar object, calls the speed method, and runs the program:

Car.java (accessing methods via an object)

 // A Java program to illustrate the method accessing
 public class Car {
   // Inside main, call two methods.
   public static void main( String[ ] args ) {
     Car myCar = new Car( );
     boolean bool = Boolean.parseBoolean( args[1] );
     if ( bool == true )  myCar.fullThrottle( );
     else  speed( Integer.parseInt( args[0] ) );
   }

   // Create a fullThrottle( ) method.
   public void fullThrottle( ) {
     System.out.println( "200" );
   }

   // Create a speed( ) method and add a parameter.
   public  void speed( int maxSpeed ) {
     System.out.println( maxSpeed );
   }
 }
shell> java Car            
  1. A custom Car class is created by using the class keyword.
  2. The fullThrottle and speed methods in the Car class are created.
  3. The fullThrottle method and the speed method will print out some text, when they are called.
  4. The speed method accepts an int parameter called maxSpeed.
  5. In order to use the Car class and its methods, we need to create an object of the Car class.
  6. Activate the main method, which is the entry point into the program.
  7. By using the new keyword, a Car object with the name myCar is created.
  8. Finally, call the fullThrottle method on the myCar object, and run the program using the name of the object (myCar), followed by a dot (.), followed by the name of the method (fullThrottle) or call the method speed(200) directly.



      Jerry tries to teach Tuffy how to    
      bell the cat (push his luck) in a last effort.