0% found this document useful (0 votes)
4 views35 pages

Introduction to Classes Objects and Methods

This lecture introduces the fundamental concepts of classes, objects, and methods in Java, emphasizing the importance of classes as templates that define the structure and behavior of objects. It explains how to create classes, define instance variables and methods, and the process of object creation and manipulation. The lecture also covers the significance of methods in interacting with class data and demonstrates how to enhance class functionality through method implementation.

Uploaded by

glorymuindisi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views35 pages

Introduction to Classes Objects and Methods

This lecture introduces the fundamental concepts of classes, objects, and methods in Java, emphasizing the importance of classes as templates that define the structure and behavior of objects. It explains how to create classes, define instance variables and methods, and the process of object creation and manipulation. The lecture also covers the significance of methods in interacting with class data and demonstrates how to enhance class functionality through method implementation.

Uploaded by

glorymuindisi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

LECTURE 4

INTRODUCTION TO CLASSES, OBJECTS


AND METHODS.

Akademia Finansów i Biznesu Vistula


mgr inż. Dominik Bielecki
Studia globalnych możliwości 1
email: d.bielecki@vistula.edu.pl
PRELUDE
Before we can go much further in our study of Java, we need to learn
about the class. The class is the essence of Java. It is the foundation
upon which the entire Java language is built because 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. Having a
basic understanding of these features will allow as to write more
sophisticated programs and better understand certain key Java elements
described in the following lectures.

Akademia Finansów i Biznesu Vistula


Studia globalnych możliwości 2
CLASS FUNDAMENTALS
Let’s begin by reviewing the basics. A class is a template 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. It is important to be clear on one issue: a
class is a logical abstraction. It is not until an object of that class has
been created that a physical representation of that class exists in
memory.
One other point: Recall that the methods and variables that constitute a
class are called members of the class. The data members are also
referred to as instance variables.
Akademia Finansów i Biznesu Vistula
Studia globalnych możliwości 3
THE GENERAL FORM OF A CLASS (1)
When we define a class, we declare its exact form and nature. We do this by specifying the instance variables that it contains and the
methods that operate on them. Although very simple classes might contain only methods or only instance variables, most real-world classes
contain both.
A class is created by using the keyword class. A simplified general form of a class definition is below:
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(parameters) {
// body of method }
}
Akademia Finansów i Biznesu Vistula
Studia globalnych możliwości 4
THE GENERAL FORM OF A CLASS (2)
Although there is no syntactic rule that enforces it, a well-designed class
should define one and only one logical entity. For example, a class that
stores names and telephone numbers will not normally also store
information about the stock market, average rainfall, sunspot cycles, or
other unrelated information. The point here is that a well-designed class
groups logically connected information. Putting unrelated information into
the same class will quickly destructure our code!
Up to this point, the classes that we have been creating have had only one
method: main( ). Soon you we will create others. However, you should
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 our
program. Also, some types of Java applications don’t require a main( ).

Akademia Finansów i Biznesu Vistula


Studia globalnych możliwości 5
DEFINING A CLASS (1)
To illustrate classes, we will develop a class that encapsulates information about
vehicles, such as cars, vans, and trucks. This class is called Vehicle, and it will
store three items of information about a vehicle: the number of passengers that it
can carry, its fuel capacity, and its average fuel consumption.
The first version of Vehicle is shown next. It defines three instance variables:
passengers, fuelcap, and mpg. Notice that Vehicle does not contain any methods.
Thus, it is currently a data-only class.
class Vehicle {
int passengers // numer of passengers
int fuealcap; // fuel capacity
int kmpl; // fuel consumption
}
Akademia Finansów i Biznesu Vistula
Studia globalnych możliwości 6
DEFINING A CLASS (2)
A class definition creates a new data type. In this case, the new data type is
called Vehicle. We will use this name to declare objects of type Vehicle.
Remember that a class declaration is only a type description; it does not
create an actual object. Thus, the preceding code does not cause any
objects of type Vehicle to come into existence.
To actually create a Vehicle object, we will use a statement like the
following:
Vehicle minivan = new Vehicle(); // create a Vehicle object called minivan
After this statement executes, minivan refers to an instance of Vehicle.
Thus, it will have “physical” reality.

Akademia Finansów i Biznesu Vistula


Studia globalnych możliwości 7
DEFINING A CLASS (3)
Each time we create an instance of a class, we are creating an object that
contains its own copy of each instance variable defined by the class. Thus, every
Vehicle object will contain its own copies of the instance variables passengers,
fuelcap, and kmpl. To access these variables, we will use the dot (.) operator. The
dot operator links the name of an object with the name of a member. The general
form of the dot operator is shown here:
object.member
Thus, the object is specified on the left, and the member is put on the right. For
example, to assign the fuelcap variable of minivan the value 16, we use the
following statement:
minivan.fuelcap = 10;
In general, we can use the dot operator to access both instance variables and
methods.

Akademia Finansów i Biznesu Vistula


Studia globalnych możliwości 8
HOW OBJECTS ARE CREATED (1)
The following line was used to declare an object of type Vehicle:
Vehicle minivan = new Vehicle();
This declaration performs two functions. First, it declares a variable called
minivan of the class type Vehicle. This variable does not define an object.
Instead, it is simply a variable that can refer to an object. Second, the
declaration creates an instance of the object and assigns to minivan a
reference to that object. This is done by using the new operator.
The new operator dynamically allocates (that is, allocates at run time)
memory for an object and returns a reference to it. This reference is,
essentially, the address in memory of the object allocated by new. This
reference is then stored in a variable. Thus, in Java, all class objects must
be dynamically allocated.
Akademia Finansów i Biznesu Vistula
Studia globalnych możliwości 9
HOW OBJECTS ARE CREATED (2)
The two steps combined in the preceding statement can be rewritten like
this to show each step individually:
Vehicle minivan; // declare referance to object
minivan = new Vehicle(); // allocate a Vehicle object
The first line declares minivan as a reference to an object of type Vehicle.
Thus, minivan is a variable that can refer to an object, but it is not an object
itself. At this point, minivan does not refer to an object. The next line
creates a new Vehicle object and assigns a reference to it to minivan. Now,
minivan is linked with an object.

Akademia Finansów i Biznesu Vistula


Studia globalnych możliwości 10
REFERENCE VARIABLES AND ASSIGNMENT
In an assignment operation, object reference variables act differently than do variables of a primitive type, such as
int. When you assign one primitive-type variable to another, the situation is straightforward. The variable on the left
receives a copy of the value of the variable on the right. When you assign one object reference variable to another, the
situation is a bit more complicated because you are changing the object that the reference variable refers to. The
effect of this difference can cause some counterintuitive results. For example, consider the following fragment:
Vehicle car1 = new Vehicle();
Vehicle car2 = car1;
At first glance, it is easy to think that car1 and car2 refer to different objects, but this is not the case. Instead, car1
and car2 will both refer to the same object. The assignment of car1 to car2 simply makes car2 refer to the same
object as does car1. Thus, the object can be acted upon by either car1 or car2. For example, after the assignment
car1.kmpl = 20;
executes, both of these println( ) statements

System.out.println(car1.kmpl);
System.out.println(car2.kmpl);

display the same value: 20.


Akademia Finansów i Biznesu Vistula
Studia globalnych możliwości 11
METHODS (1)
As I explained, instance variables and methods are constituents of classes.
So far, the Vehicle class contains data, but no methods. Although data-only
classes are perfectly valid, most classes will have methods. Methods are
subroutines that manipulate the data defined by the class and, in many
cases, provide access to that data. In most cases, other parts of our
program will interact with a class through its methods.
A method contains one or more statements. In well-written Java code, each
method performs only one task. Each method has a name, and it is this
name that is used to call the method. In general, you can give a method
whatever name you please. However, remember that main( ) is reserved for
the method that begins execution of yourprogram. Also, don’t use Java’s
keywords for method names.

Akademia Finansów i Biznesu Vistula


Studia globalnych możliwości 12
METHODS (2)
The general form of a method is shown here:
ret-type name(parameter-list){ // body of method }
Here, ret-type specifies the type of data returned by the method. This can
be any valid type, including class types that you create. If the method does
not return a value, its return type must be void. The name of the method is
specified by name. This can be any legal identifier other than those already
used by other items within the current scope. The parameter-list is a
sequence of type and identifier pairs separated by commas. Parameters
are essentially variables that receive the value of the arguments passed to
the method when it is called. If the method has no parameters, the
parameter list will be empty.
Akademia Finansów i Biznesu Vistula
Studia globalnych możliwości 13
ADDING A METHOD TO THE VEHICLE CLASS (1)
As I just explained, the methods of a class typically manipulate and provide
access to the data of the class. With this in mind, recall that main( ) in the
preceding examples computed the range of a vehicle by multiplying its fuel
consumption rate by its fuel capacity. While technically correct, this is not the
best way to handle this computation. The calculation of a vehicle’s range is
something that is best handled by the Vehicle class itself. The reason for this
conclusion is easy to understand: the range of a vehicle is dependent upon the
capacity of the fuel tank and the rate of fuel consumption, and both of these
quantities are encapsulated by Vehicle. By adding a method to Vehicle that
computes the range, you are enhancing its object-oriented structure. To add a
method to Vehicle, specify it within Vehicle’s declaration. For example, the
following slide with version of Vehicle contains a method called range( ) that
displays the range of the vehicle.

Akademia Finansów i Biznesu Vistula


Studia globalnych możliwości 14
ADDING A METHOD TO THE VEHICLE CLASS (2)

Akademia Finansów i Biznesu Vistula


Studia globalnych możliwości 15
ADDING A METHOD TO THE VEHICLE CLASS (3)
Let’s look at the key elements of this program, beginning with the range( )
method itself. The first line of range( ) is
void rane() {
This line declares a method called range that has no parameters. Its return type
is void. Thus, range( ) does not return a value to the caller. The line ends with the
opening curly brace of the method body.
The body of range( ) consists solely of this line:
System.out.println("Range is: " + fuelCap * kmpl);
This statement displays the range of the vehicle by multiplying fuelcap by kmpl.
Since each object of type Vehicle has its own copy of fuelcap and kmpl, when
range( ) is called, the range computation uses the calling object’s copies of those
variables. The range( ) method ends when its closing curly brace is encountered.
This causes program control to transfer back to the caller.
Akademia Finansów i Biznesu Vistula
Studia globalnych możliwości 16
ADDING A METHOD TO THE VEHICLE CLASS (4)
Next, look closely at this line of code from inside main( ):
minivan.range();
This statement invokes the range( ) method on minivan. That is, it calls range( ) relative
to the minivan object, using the object’s name followed by the dot operator. 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 following the call.
In this case, the call to minivan.range( ) displays the range of the vehicle defined by
minivan. In similar fashion, the call to sportsCar.range( ) displays the range of the
vehicle defined by sportsCar. Each time range( ) is invoked, it displays the range for the
specified object.
There is something very important to notice inside the range( ) method: the instance
variables fuelcap and kmpl are referred to directly, without preceding them with an
object name or the dot operator. When a method uses an instance variable that is
defined by its class, it does so directly, without explicit reference to an object and
without use of the dot operator.
Akademia Finansów i Biznesu Vistula
Studia globalnych możliwości 17
RETURNING FROM A METHOD
In general, there are two conditions that cause a method to return—first, as the range() method
in the preceding example shows, when the method’s closing curly brace is encountered. The
second is when a return statement is executed. There are two forms of return—one for use in
void methods (those that do not return a value) and one for returning values. The first form is
examined here. The next section explains how to return values.
In a void method, you can cause the immediate termination of a method by using form of
return. When return statement executes, program control returns to the caller, skipping any
remaining code in the method. For example, consider this method:
void myMethod() {
int i;
for(i=0; i<10; i++){
if(i == 5) return; // stop at 5
System.out.println(); }}
Here, the for loop will only run from 0 to 5, because once i equals 5, the method returns. It is ok
to have multiple return statements in a method, especially when there are two or more routes
out of it.
Akademia Finansów i Biznesu Vistula
Studia globalnych możliwości 18
RETURNING A VALUE (1)
Although methods with a return type of void are not rare, most methods will
return a value. In fact, the ability to return a value is one of the most useful
features of a method. We have already seen one example of a return value: when
we used the sqrt( ) function to obtain a square root.
Return values are used for a variety of purposes in programming. In some cases,
such as with sqrt( ), the return value contains the outcome of some calculation.
In other cases, the return value may simply indicate success or failure. In still
others, it may contain a status code.
Methods return a value to the calling routine using this form of return:
return value;
Here, value is the value returned. This form of return can be used only with
methods that have a non-void return type. Furthermore, a non-void method must
return a value by using this form of return.
Akademia Finansów i Biznesu Vistula
Studia globalnych możliwości 19
RETURNING A VALUE (2)
We can use a return value to improve the implementation of range( ).
Instead of displaying the range, a better approach is to have range( )
compute the range and return this value. Among the advantages to this
approach is that we can use the value for other calculations. Program on
the next slide with modifies range( ) to return the range rather than
displaying it.

Akademia Finansów i Biznesu Vistula


Studia globalnych możliwości 20
RETURNING A VALUE (3)

Akademia Finansów i Biznesu Vistula


Studia globalnych możliwości 21
USING PARAMETERS
It is possible to pass one or more values to a method when the method is
called. Recall that a value passed to a method is called an argument. Inside
the method, the variable that receives the argument is called a parameter.
Parameters are declared inside the parentheses that follow the method’s
name. The parameter declaration syntax is the same as that used for
variables. A parameter is within the scope of its method, and aside from its
special task of receiving an argument, it acts like any other local variable.

Akademia Finansów i Biznesu Vistula


Studia globalnych możliwości 22
ADDING A PARAMETERIZED METHOD TO
VEHICLE (1)
We can use a parameterized method to add a new feature to the Vehicle class:
the ability to compute the amount of fuel needed for a given distance. This new
method is called fuelNeeded( ). This method takes the number of km that we
want to drive and returns the number of liters of gas required. The fuelNeeded( )
method is defined like this:
double fuelNeeded(int km){
return (double) km/kmpl;
}
Notice that this method returns a value of type double. This is useful since the
amount of fuel needed for a given distance might not be a whole number. The
entire Vehicle class that includes fuelNeeded( ) is shown on the next slide:
Akademia Finansów i Biznesu Vistula
Studia globalnych możliwości 23
ADDING A PARAMETERIZED METHOD TO
VEHICLE (2)

Akademia Finansów i Biznesu Vistula


Studia globalnych możliwości 24
CONSTRUCTORS (1)
In the preceding examples, the instance variables of each Vehicle object had to
be set manually using a sequence of statements, such as:
sportsCar.passengers = 2;
sportsCar.fuelCap = 14;
sportsCar.kmpl = 12;
An approach like this would never be used in commercial written Java code.
Aside from being error prone (we might forget to set one of the fields), there is
simply a better way to accomplish this task: the constructor.
A constructor initializes an object when it is created. It has the same name as its
class and is syntactically similar to a method. However, constructors have no
explicit return type. Typically, you will use a constructor to give initial values to
the instance variables defined by the class, or to perform any other startup
procedures required to create a fully formed object.
Akademia Finansów i Biznesu Vistula
Studia globalnych możliwości 25
CONSTRUCTORS (2)
All classes have constructors, whether you define one or not, because Java
automatically provides a default constructor. In this case, non-initialized
member variables have their default values, which are zero, null, and false,
for numeric types, reference types, and booleans, respectively. Once you
define your own constructor, the default constructor is no longer used.
Here is a simple example that uses a constructor:

Akademia Finansów i Biznesu Vistula


Studia globalnych możliwości 26
CONSTRUCTORS (3)
In this example, the constructor for MyClass assigns the instance variable
x of MyClass the value 10. This constructor is called by new when an
object is created. For example, in the line:
MyClass t1 = new MyClass();
the constructor MyClass( ) is called on the t1 object, giving t1.x the value
10. The same is true for t2. After construction, t2.x has the value 10.

Akademia Finansów i Biznesu Vistula


Studia globalnych możliwości 27
PARAMETERIZED CONSTRUCTORS
In the preceding example, a parameter-less constructor was used.
Although this is fine for some situations, most often we will need a
constructor that accepts one or more parameters. Parameters are added to
a constructor in the same way that they are added to a method: just
declare them inside the parentheses after the constructor’s name. For
example, here, MyClass is given a parameterized constructor:

Akademia Finansów i Biznesu Vistula


Studia globalnych możliwości 28
ADDING A CONSTRUCTOR TO THE VEHICLE
CLASS (1)
We can improve the Vehicle class by adding a constructor that
automatically initializes the passengers, fuelCap, and kmpl fields when an
object is constructed. You should pay should special attention to how
Vehicle objects are created.

Akademia Finansów i Biznesu Vistula


Studia globalnych możliwości 29
ADDING A CONSTRUCTOR TO THE VEHICLE
CLASS (2)

Akademia Finansów i Biznesu Vistula


Studia globalnych możliwości 30
ADDING A CONSTRUCTOR TO THE VEHICLE
CLASS (3)
Both minivan and sportsCar are initialized by the Vehicle( ) constructor
when they are created. Each object is initialized as specified in the
parameters to its constructor. For example, in the following line,
Vehicle sportsCar = new Vehicle(2,14,12);
the values 7, 16, and 21 are passed to the Vehicle( ) constructor when new
creates the object. Thus, minivan’s copy of passengers, fuelCap, and kmph
will contain the values 7, 16, and 21, respectively. The output from this
program is the same as the previous version.

Akademia Finansów i Biznesu Vistula


Studia globalnych możliwości 31
THE NEW OPERATOR REVISITED
Now that we know more about classes and their constructors, let’s take a closer look at
the new operator. In the context of an assignment, the new operator has this general
form:
class-var = new class-name(arg-list);
Here, class-var is a variable of the class type being created. The class-name is the name
of the class that is being instantiated. The class name followed by a parenthesized
argument list (which can be empty) specifies the constructor for the class. If a class
does not define its own constructor, new will use the default constructor supplied by
Java. Thus, new can be used to create an object of any class type. The new operator
returns a reference to the newly created object, which (in this case) is assigned to
class-var.
Since memory is finite, it is possible that new will not be able to allocate memory for an
object because insufficient memory exists. If this happens, a run-time exception will
occur. (We will learn about exceptions later) For the programs during our labs, we won’t
need to worry about running out of memory, but you will need to consider this
possibility in real-world programs that you write.
Akademia Finansów i Biznesu Vistula
Studia globalnych możliwości 32
GARBAGE COLLECTION (1)
As we have seen, objects are dynamically allocated from a pool of free memory
by using the new operator. As explained, memory is not infinite, and the free
memory can be exhausted. Thus, it is possible for new to fail because there is in
sufficient free memory to create the desired object. For this reason, a key
component of any dynamic allocation scheme is the recovery of free memory
from unused objects, making that memory available for subsequent reallocation.
In some programming languages, the release of previously allocated memory is
handled manually. However, Java uses a different, more trouble-free approach:
garbage collection.
Java’s garbage collection system reclaims objects automatically—occurring
transparently, behind the scenes, without any programmer intervention. It works
like this: When no references to an object exist, that object is assumed to be no
longer needed, and the memory occupied by the object is released. This recycled
memory can then be used for a subsequent allocation.
Akademia Finansów i Biznesu Vistula
Studia globalnych możliwości 33
GARBAGE COLLECTION (2)
Garbage collection occurs only sporadically during the execution of your
program. It will not occur simply because one or more objects exist that
are no longer used. For efficiency, the garbage collector will usually run
only when two conditions are met: there are objects to recycle, and there is
a reason to recycle them. Remember, garbage collection takes time, so the
Java runtime system does it only when it is appropriate. Thus, we can’t
know precisely when garbage collection will take place.

Akademia Finansów i Biznesu Vistula


Studia globalnych możliwości 34
THANK YOU

Więcej na: Akademia Finansów i Biznesu Vistula


ul. Stokłosy 3
02-787 Warszawa
www.vistula.edu.pl
Akademia Finansów i Biznesu Vistula (obok stacji metro Stokłosy) 35
Studia globalnych możliwości

You might also like