







Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!








Introduction Whenever you begin to learn a new programming language the first program that you should write in the new language is the classic “Hello world” program. This program is shown below. Enter this program and execute it before you attempt to do any other Java program. This very simple program will allow you to use the text editor to enter the program, compile and execute your program. The Class The class is the foundation of the Java language. The class defines the nature of an object. As such, the class forms the basis for object-oriented programming in Java. Within a class are defined data and code that acts upon that data. The code is contained in methods. Classes, objects, and methods are fundamental to Java. All Java program activity occurs within a class. A class is a template (prototype, blueprint, etc.) that defines the form of an object. It specifies both the data and the code that will operate on that data. Java uses a class specification to construct objects. Objects are instances of a class. Thus, a class is essentially a set of plans that specify how to build an object. The process of creating or building an instance of a class is called instantiation. An object has no physical representation in memory until it has been instantiated. Just like an architect’s blueprint for a house, until a house is built according to the blueprint, it doesn’t exist. The methods and variables that constitute a class are called members of the class. The data members are also referred to as instance variables. When COP 3503 – Computer Science II – Java Notes # Introduction To Java /* This is a simple Java program called the “Hello World” program. Name the text file in which you store this code: Example.java */ class Example { //A Java program begins with a call to main( ). public static void main (String args[]) { System.out.println(“Hello World!”); }// end main }//end class Example
you define a class, you are declaring its exact form and nature. You do this by specifying the instance variables that it contains and the methods that operate on those instance variables. A class in Java is created using the following class definition form: Class declaration in Java Although there are no syntactic rules that enforce it, a well-designed class should define one and only one logical entity. For example, a class which stores student names and telephone numbers would not normally also store the average amount of rainfall in Orlando. A well-designed class groups logically connected information. Putting unrelated information into the same class will very quickly destructure your program. Notice that the general form of a class does not specify a main( ) method. A main( ) method is required only if that class is the starting point for your program. (Also, applets don’t require a main( ).) To illustrate the concept of a class, we’ll develop a class the encapsulates information about vehicles, such as cars, vans, and trucks. We’ll call this class Vehicles and to begin with we’ll store three attributes for a vehicle (later we’ll probably add some additional attributes): the number of passengers that it can carry, the size of its fuel tank, and its average fuel consumption (miles/gallon). Let’s start simple and define our class and the three instance variables we described above. class classname { // declare instance variables type var1; type var2; // … type varN //declare methods type method1 (parameters) { //body of method } type method2 (parameters) { //body of method } // … type methodN (parameter) { //body of method N } }//end class
Example 1 Notice that since the main( ) method is in the class VehicleDemo and not in the class Vehicle that you call the file which stores this code VehicleDemo.java and not Vehicle.java. When you compile this program you will find that two .class files have been created by the compiler, one for Vehicle and one for VehicleDemo. The Java compiler automatically puts each class into its own .class file. It is not necessary that both Vehicle and VehicleDemo be in the same source file. You could put each class in its own file, called Vehicle.java and VehicleDemo.java, respectively. To run this program, you must execute VehicleDemo.class. If you do this you should see the following output: Ferrari can carry 2 with a range of 100 miles The new Statement Consider the new statement from the last example program in which the ferrari was created. This declaration performs two functions. First, it declares a variable called ferrari of the class type Vehicle. This variable does not define an /* A program that uses the Vehicle class Name this file: VehicleDemo.java */ class Vehicle { int passengers; // number of passengers the vehicle can carry int fuelcapacity; // size of the fuel tank in gallons int mpg; // fuel consumption in miles/gallon } //This class simply declares an object of type Vehicle. class VehicleDemo { public static void main (String args[]) { Vehicle ferrari = new Vehicle( ); int range; // assign values to the instance variables for the ferrari ferrari.passengers = 2; ferrari.fuelcapacity = 20; ferrari.mpg = 5; // compute the range assuming a full tank of fuel is loaded. range = ferrari.fuelcapacity * ferrari.mpg; System.out.println(“Ferrari can carry “ + ferrari.passengers + “with a range of ”
object. Instead, it is simply a variable that can refer to an object of type Vehicle. Second, the declaration creates a physical copy of the object and assigns to ferrari a reference to that object. This is done by using the new operator. The new operator dynamically allocates memory for an object and returns a reference to it. This reference is basically the address in memory of the object allocated by new. This reference is then stored in the variable ferrari. In Java, all class objects are dynamically allocated. To illustrate this further, consider our original statement rewritten as: The first line declares ferrari as a reference to an object of type Vehicle. Thus, ferrari is a variable that can refer to an object, but it is not an object itself. At this point, ferrari contains the value null , which means that it does not refer to an object. The next line creates a new Vehicle object and assigns a reference to it to ferrari. Now, ferrari is linked to an object. These two operations are typically performed simultaneously and written together as we did in the program example. Reference Variables and Assignments In an assignment operation, object reference variables act differently than do variables of a simple type, such as an integer. When you assign one simple type to another, the situation is quite simple: the variable on the left hand side of the assignment operator receives a copy of the value of the variable on the right hand side of the assignment operator. When you assign an object reference variable to another you are potentially changing the object that the reference variable refers to. The effect of this difference can cause some counterintuitive results, unless you are aware of what is happening. Consider the following code fragment: At first glance, you might think that ferrari and mercedes refer to different objects, but this is not the case, Instead, ferrari and mercedes will both refer to the same object. ferrari mercedes Vehicle ferrari; //declare a reference variable to an object ferrari = new Vehicle( ); //allocate a Vehicle object Vehicle ferrari = new Vehicle( ); Vehicle mercedes = ferrari; object
name, and it is this name which is used to call the method. Shown below is the general form for a method: Method declaration in Java Where return-type is the type of the data returned by the method. This can be any valid type, including class types that you have created. If the method does not return a value, its return type must be void. The parameter list is a sequence of type and identifier pairs separated by commas. Parameters are basically variables that receive the value of the arguments passed to the method when it is called (invoked). If the method has no parameters, the parameter list will be empty. In Example 1 above, we used the main method to calculate the range that a vehicle could cover on a tank of fuel. While this worked ok, it is not the best way to handle this calculation because this is something that should be handled within the Vehicle class itself. The reason this is so is easy to understand. The range of a vehicle is dependent upon the capacity of its fuel tank and the rate at which is consumes fuel. These are both quantities (attributes of a vehicle) that we have encapsulated in the Vehicle class. Therefore, this calculation should also be performed within the class where these instance variables reside. Let’s rewrite our program to incorporate a method to perform this calculation inside the Vehicle class. Looking at Example 3, notice in the range( ) method of the Vehicle class that the dot notation is not used since the instance variables are contained within the same class as the method which is using them. Also notice that since each object of type Vehicle has its own copy of fuelcapacity and mpg , when the range( ) method is called, the range computation uses the calling object’s copies of these instance variables. So the statement ferrari.range( ) invokes the method range( ) on the object referenced by ferrari. When a method is called, program control is transferred to the method. When the method terminates, control is transferred back to the caller, and execution resumes with the line of code immediately after (immediately logically after) the call. return-type name (parameter-list) { //body of the method } //end of method
Example 3 When the program of Example 3 is executed the output will be: /* A program that uses the Vehicle class extended to include a method Name this file: VehicleDemo2.java */ class Vehicle { int passengers; // number of passengers the vehicle can carry int fuelcapacity; // size of the fuel tank in gallons int mpg; // fuel consumption in miles/gallon //calculate the range of a vehicle. void range ( ) { System.out.println( “Range is “ + fuelcapacity * mpg + “ miles”); }//end method range }//end class Vehicle //This class simply declares an object of type Vehicle and uses it. class VehicleDemo2 { public static void main (String args[]) { Vehicle ferrari = new Vehicle( ); Vehicle mercedes = new Vehicle( ); // assign values to the instance variables for the ferrari ferrari.passengers = 2; ferrari.fuelcapacity = 20; ferrari.mpg = 5; // assign values ot the instance variables for the mercedes mercedes.passengers = 4; mercedes.fuelcapacity = 19; mercedes.mpg = 25; // compute the range assuming a full tank of fuel is loaded. System.out.print(“Ferrari can carry “ + ferrari.passengers + “.”); ferrari.range( ); System.out.print(“Mercedes can carry “ + mercedes.passengers + “.”); mercedes.range( ); }//end main }//end class VehicleDemo Ferrari can carry 2. Range is 100 miles Mercedes can carry 4. Range of 475 miles
Example 4 When the program of Example 4 is executed the output will be: Example 4 When executed, Example 4 will produce the following output: COP 3503 – Java Notes #1 - 10 /* A program that uses the Vehicle class extended to include a method which returns a value Name this file: VehicleDemo3.java */ class Vehicle { int passengers; // number of passengers the vehicle can carry int fuelcapacity; // size of the fuel tank in gallons int mpg; // fuel consumption in miles/gallon //calculate the range of a vehicle. int range ( ) { return fuelcapacity * mpg; }//end method range }//end class Vehicle //This class simply declares an object of type Vehicle and uses it. class VehicleDemo3 { public static void main (String args[]) { Vehicle ferrari = new Vehicle( ); Vehicle mercedes = new Vehicle( ); int ferrari_range, mercedes_range; // assign values to the instance variables for the ferrari ferrari.passengers = 2; ferrari.fuelcapacity = 20; ferrari.mpg = 5; // assign values ot the instance variables for the mercedes mercedes.passengers = 4; mercedes.fuelcapacity = 19; mercedes.mpg = 25; // compute the range assuming a full tank of fuel is loaded. ferrari_range = ferrari.range( ); mercedes_range = mercedes.range( ); System.out.print(“Ferrari can carry “ + ferrari.passengers + “with a range of “
Example 5 The output from Example 5 when executed will be: