Page 1 of 1

## JAVA CLASS DESIGN “E = MC^2” TUTORIAL Rate Topic: 1 Votes //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=247347&amp;s=1c28acfb1a4a271960b418b0e5544193&md5check=' + ipb.vars['secure_hash'], cur_rating: 5, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 Elcric

• D.I.C Regular

Reputation: 102
• Posts: 453
• Joined: 02-May 09

Posted 15 September 2011 - 04:29 PM

JAVA
“ENERGY EQUALS MASS TIMES
THE SPEED OF LIGHT SQUARED”
TUTORIAL

CONTENTS
• I. INTRODUCTION
• II. ENERGY EQUALS MASS TIMES THE SPEED OF LIGHT SQUARED
• III. CLASS
• IV. INSTANCE VARIABLES
• V. CONSTRUCTORS
• VI. INSTANTIATING AN OBJECT
• VII. CONSTANTS
• VIII. MAIN METHOD
• IX. METHODS
• X. EXAMPLE PROGRAM
• XI. REFERENCES

I. INTRODUCTION

Hello; nice to meet you. Welcome to the “Java ‘Energy Equals Mass Times the Speed of Light Squared’ Tutorial.”

This tutorial was prepared using Microsoft Windows, NetBeans IDE 7.0.1 and JDK 1.7.

If you find any errors or better ways of presenting the information please post them as tutorial comments.

II. ENERGY EQUALS MASS TIMES THE SPEED OF LIGHT SQUARED

The “Java ‘Energy Equals Mass Times the Speed of Light Squared’ Tutorial” title was selected to introduce the reader to the Java methods used to demonstrate key points discussed in the tutorial.

In order to create tutorial discussion examples we will write a Java program to compute, “Energy equals mass times the speed of light squared.” Our discussion examples will include a Java energy class and an object of that class, and of course instance variables and methods for computations and printouts.

III. CLASS

Our Java source code begins in the following order: first, a package declaration; second, an import declaration; and third, a class declaration.

The “EEqualsMCSquaredPackage” will be used to contain our class “EEqualsMCSquaredClass.” Java uses packages to group classes in order to make libraries.

```/*
* classes are organized into packages;
* therefore, if you want to reuse an existing
* class, instead of copying the class
* into your program you import the package
* containing the class
*/
package EEqualsMCSquaredPackage;

```

We will need to square the speed of light; therefore, we import “java.lang.Math.*” in order to make the tutorial coding easier to read.
```/*
* static import of math class methods
* enable calling each Math class method by name
* without writing Math in front of
* the Math method
*/
import static java.lang.Math.*;

```

Our class declaration starts with the “public” access modifier keyword; therefore, it can be accessed from anywhere.

Next the class declaration has the keyword “class” followed by the class’s name “EEqualsMCSquaredClass.”

Immediately following the class name is a set of open and closed braces “{ }” which will enclose the body of the class.

```/*
* class declaration
*/
public class EEqualsMCSquaredClass {

}  // end class EEqualsMCSquaredClass

```

IV. INSTANCE VARIABLES

Local variables are declared and used within a method and when the method terminates the local variables are lost.

An object has attributes (instance variables also called data fields or class declaration variables) that are declared when their class is declared and are used within its class. Each object has its own copy of the instance variables. When an object is created Java automatically calls a constructor which initializes the objects instance variables. The life of the object’s copy of its instance variables is the life of the object.

The instance variables for the example program are as follows:

```/*
* class declaration
*/
public class EEqualsMCSquaredClass {

private double M;    // mass of atoms
private double E;     // energy released
private double SD;   // sticks of dynamite equivalent to E

```

The access modifiers: “public,” “private, “protected” and the default modifier (no modifier) control access to a class’s instance variables. The “private” instance variables can only be accessed by a “public” method from inside their class. The “public” instance variables can be accessed from anywhere in the application. The access to “protected” instance variables is between the access of “public” and “private.” You have to be in the same package to access “protected” instance variables from inside their class.

V. CONSTRUCTORS

As previously mentioned above, each object has its own copy of the instance variables. When an object is created Java automatically calls a constructor which initializes the objects instance variables. The life of the object’s copy of its instance variables is the life of the object.

The instance variable constructors for the example program are as follows:

```	/*
* object created
* no arguments passed in
* default constructor executed
*/
public EEqualsMCSquaredClass( ){
super();

System.out.println( "\n     ****************************************************  \n" );
System.out.println( "     OBJECT CREATED\n" );
System.out.println( "     NO ARGUMENTS PASSED IN\n" );
System.out.println( "     DEFAULT CONSTRUCTOR EXECUTED!\n" );
System.out.println( "     ****************************************************  \n" );

}

/*
* object created
* three arguments passed in
* and they match constructor
* parameters by type and number
*/
public EEqualsMCSquaredClass( double m, double e, double sd ){

M = m;
E = e;
SD = sd;

System.out.println( "\n     ****************************************************  \n" );
System.out.println( "     OBJECT CREATED\n" );
System.out.println( "     THREE ARGUMENTS PASSED IN\n" );
System.out.println( "     AND THEY MATCH CONSTRUCTOR PARAMETERS BY TYPE AND NUMBER\n" );
System.out.println( "     CONSTRUCTOR EXECUTED!\n" );
System.out.println( "     M   = " + M + "\n" );
System.out.println( "     E   = " + E + "\n" );
System.out.println( "     SD  = " + SD + "\n" );
System.out.println( "     ****************************************************  \n" );

}

```

The constructor declaration is the control in the sense that the constructor’s parameters in the constructor declaration have to match the arguments passed in to the constructor by number and type to execute the constructor.

All constructors are located within the class and outside of the class methods.

Every class has at least one constructor. If you declare a default constructor, Java will not create a default constructor for you. The first line inside a default constructor must be a call to the super class constructor “super();” or “this” but not both.

A constructor method:

A. Can be used to assign initial values to an object’s instance variables.

B. Does not have any return type.

C. Has the same name as the class it is in.

D. Has the same access modifier as the class it is in.

F. The “this” keyword can be used to ensure an object accesses its own attributes (instance variables also called data fields or class declaration variables).

VI. INSTANTIATING AN OBJECT

(So far we have presented the tutorial in the same order as the example program’s code. However, “constructors” and “instantiating an object” go hand in hand; therefore, to make it easier to explain things we will jump ahead. However, the “instantiating an object” code is located where it is in the example program because the M, E, SD local variable arguments we need to pass to the constructor have not been coded until then.)

When a new object of a class is created a constructor for that class is called automatically to initialize the attributes (instance variables also called data fields or class declaration variables) of the new object.

We start our object declaration with “EEqualsMCSquaredClass” the class name. Next we declare the name of our object, which in the example program is “E1.” Then we type the assignment symbol “=” followed by the keyword “new.” We end the object declaration with the class name “EEqualsMCSquaredClass” followed by an open and closed parenthesis “( M, E, SD )” containing the “arguments” we are passing to the constructor and a statement ending semicolon “;.”

For example:

```
/*
* creates a new EEqualsMCSquaredClass
* class object named E1
* passes three arguments
* to the constructor
*/
EEqualsMCSquaredClass E1 = new EEqualsMCSquaredClass( M, E, SD );

```

The arguments passed from the instantiating an object code must match the constructor’s parameters by number and type; however, they do not have to have the same name.
VII. CONSTANTS
Within the class body, after the constructors, we declare two constants: “C” the speed of light in meters per second, and “D” the Joules of energy in one stick of dynamite. For example:

```	/*
* C = speed of light, measured in meters per second (mps)
*/
public static final double C = 299792458;

/*
* D = Joules of energy in one stick of dynamite
*/
public static final double D = 2100000;

```

The declaration of “C” starts with the “public” access modifier keyword. Placing the keyword “static” before the return type in the declaration declares the variable static which means “C” is a class variable common to all objects of the class. The keyword “final” means the class variable “C” is a constant. Also, “final” is used to ensure “C,” the speed of light, is not modifiable by assignment.

We follow the same steps to declare “D.”

VIII. MAIN METHOD

The method main begins the execution of the application and is shown as follows:
```		/*
* main method begins execution of Java application
*/
public static void main( String[] args ){

}  //  end main

```

The main method declares the local variables and makes the method calls.

A. LOCAL VARIABLES

The following local variables are declared and used within the main method; and, when the main method terminates the local variables are lost.

The type of the function call must match the return type of the method being called.

Each function’s arguments passed to a method must match the number and type of the called method’s parameters.

```
/*
* M = the total mass of hydrogen atoms,
* measured in kilograms (kg), in one kg of pure water.
*/
double M = .111;

/*
* computes j of energy released
* equals kg of atom mass times the
* mps of light squared
*/
double E = setEnergyReleased( M, C );

/*
* computes equivalent sticks of dynamite
*/
double SD = setSticksOfDynamite( E, D );

```

B. METHOD CALLS

The arguments passed to the methods must match the called method’s parameters by number and type.

Notice in the examples below we are using the new object we created, named E1, to call methods. We are doing this to pass the appropriate attributes of E1 to the method as arguments. If we created multiple objects, each object we created would have its own unique attributes.

```
/*
* calls method using
* new object
* and  prints kg of atom mass
*/
E1.one( M );

/*
* calls method using
* new object
* and prints mps of light
*/
E1.two( C );

/*
* calls method using
* new object
* and prints j of energy released
*  and prints equivalent sticks of dynamite
*/
E1.three( E, SD );

```

IX. METHODS

As shown below, the method’s parameters control the number and type of arguments passed to the method from the calling function.

Each method’s type must be the type returned by the method. The function calling the method must have the same type as the type returned by the method.

```	/*
* computes j of energy released
* equals kg of atom mass times the
* mps of light squared
*/
public static double setEnergyReleased( double M, double C ) {

return ( M * pow( C, 2 ) );

}  // end getEnergyReleased method

/*
* computes equivalent sticks of dynamite
*/
public static double setSticksOfDynamite( double E, double D ) {

return ( E / D );

}  // end getSticksOfDynamite method

//  prints kg of atom mass
public void one( double M ) {

System.out.println( "Given that:\n" );
System.out.println( "1.  One kilogram (kg) of pure water contains a mass of " );
System.out.println("    M = " + M + " kg of hydrogen atoms.\n" );

}  // end method one

// prints mps of light
public void two( double C ) {

System.out.println( "2.  And, C = the speed of light which is approximately" );
System.out.println( "    " + C + " meters per second (mps).\n");

}  // end method two

/*
*  prints j of energy released
*  prints equivalent sticks of dynamite
*/
public void three( double E, double SD ) {

System.out.println( "3.  Then, using the equation E = M ( C * C )" );
System.out.println( "    the energy which could be released from one kilogram of pure water," );
System.out.println( "    excluding the energy released by the oxygen atoms therein, is approximately" );
System.out.println( "    " + E + " Joules (j).\n" );
System.out.println( "    A stick of dynamite contains roughly 2.1E6 Joules of energy.\n" );
System.out.println( "    Therefore, the energy released equals approximately " + SD + " sticks of dynamite!\n" );

}  // end method three

```

X. EXAMPLE PROGRAM

The example program is as follows:
```/*
* classes are organized into packages;
* therefore, if you want to reuse an existing
* class, instead of copying the class
* into your program you import the package
* containing the class
*/
package EEqualsMCSquaredPackage;

/*
* static import of math class methods
* enable calling each Math class method by name
* without writing Math in front of
* the Math method
*/
import static java.lang.Math.*;

/*
* class declaration
*/
public class EEqualsMCSquaredClass {

private double M;    // mass of atoms
private double E;     // energy released
private double SD;   // sticks of dynamite equivalent to E

/*
* object created
* no arguments passed in
* default constructor executed
*/
public EEqualsMCSquaredClass( ){
super();

System.out.println( "\n     ****************************************************  \n" );
System.out.println( "     OBJECT CREATED\n" );
System.out.println( "     NO ARGUMENTS PASSED IN\n" );
System.out.println( "     DEFAULT CONSTRUCTOR EXECUTED!\n" );
System.out.println( "     ****************************************************  \n" );

}

/*
* object created
* three arguments passed in
* and they match constructor
* parameters by type and number
*/
public EEqualsMCSquaredClass( double m, double e, double sd ){

M = m;
E = e;
SD = sd;

System.out.println( "\n     ****************************************************  \n" );
System.out.println( "     OBJECT CREATED\n" );
System.out.println( "     THREE ARGUMENTS PASSED IN\n" );
System.out.println( "     AND THEY MATCH CONSTRUCTOR PARAMETERS BY TYPE AND NUMBER\n" );
System.out.println( "     CONSTRUCTOR EXECUTED!\n" );
System.out.println( "     M   = " + M + "\n" );
System.out.println( "     E   = " + E + "\n" );
System.out.println( "     SD  = " + SD + "\n" );
System.out.println( "     ****************************************************  \n" );

}

/*
* C = speed of light, measured in meters per second (mps)
*/
public static final double C = 299792458;

/*
* D = Joules of energy in one stick of dynamite
*/
public static final double D = 2100000;

/*
* main method begins execution of Java application
*/
public static void main(String[] args) {

/*
* M = the total mass of hydrogen atoms,
* measured in kilograms (kg), in one kg of pure water.
*/
double M = .111;

/*
* computes j of energy released
* equals kg of atom mass times the
* mps of light squared
*/
double E = setEnergyReleased( M, C );

/*
* computes equivalent sticks of dynamite
*/
double SD = setSticksOfDynamite( E, D );

/*
* creates a new EEqualsMCSquaredClass
* class object named E1
* passes three arguments
* to the constructor
*/
EEqualsMCSquaredClass E1 = new EEqualsMCSquaredClass( M, E, SD );

/*
* calls method using
* new object
* and  prints kg of atom mass
*/
E1.one( M );

/*
* calls method using
* new object
* and prints mps of light
*/
E1.two( C );

/*
* calls method using
* new object
* and prints j of energy released
*  and prints equivalent sticks of dynamite
*/
E1.three( E, SD );

}  // end main

/*
* computes j of energy released
* equals kg of atom mass times the
* mps of light squared
*/
public static double setEnergyReleased( double M, double C ) {

return ( M * pow( C, 2 ) );

}  // end getEnergyReleased method

/*
* computes equivalent sticks of dynamite
*/
public static double setSticksOfDynamite( double E, double D ) {

return ( E / D );

}  // end getSticksOfDynamite method

//  prints kg of atom mass
public void one( double M ) {

System.out.println( "Given that:\n" );
System.out.println( "1.  One kilogram (kg) of pure water contains a mass of " );
System.out.println("    M = " + M + " kg of hydrogen atoms.\n" );

}  // end method one

// prints mps of light
public void two( double C ) {

System.out.println( "2.  And, C = the speed of light which is approximately" );
System.out.println( "    " + C + " meters per second (mps).\n");

}  // end method two

/*
*  prints j of energy released
*  prints equivalent sticks of dynamite
*/
public void three( double E, double SD ) {

System.out.println( "3.  Then, using the equation E = M ( C * C )" );
System.out.println( "    the energy which could be released from one kilogram of pure water," );
System.out.println( "    excluding the energy released by the oxygen atoms therein, is approximately" );
System.out.println( "    " + E + " Joules (j).\n" );
System.out.println( "    A stick of dynamite contains roughly 2.1E6 Joules of energy.\n" );
System.out.println( "    Therefore, the energy released equals approximately " + SD + " sticks of dynamite!\n" );

}  // end method three

}  // end class EEqualsMCSquaredClass

```

XI. REFERENCES

CS106A Computer Science I: Programming Methodology Lectures by Mehran Sahami, Associate Professor, Computer Science Department (450 Serra Mall, Stanford, CA: Stanford University, 2007).

Java How To Program Eighth Edition by Paul Deitel and Harvey Deitel (Upper Saddle River, N.J.: Pearson Education, Inc., 2010).

Is This A Good Question/Topic? 1

Page 1 of 1

 .related ul { list-style-type: circle; font-size: 12px; font-weight: bold; } .related li { margin-bottom: 5px; background-position: left 7px !important; margin-left: -35px; } .related h2 { font-size: 18px; font-weight: bold; } .related a { color: blue; }