Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
43 views

Introducing Classes, Objects, and Methods

This document introduces key concepts in object-oriented programming with Java including classes, objects, methods, constructors, and garbage collection. A class defines the form of an object including its data and code. An object is an instance of a class. Methods define reusable blocks of code that operate on an object's data. Constructors initialize an object's data when it is created. Garbage collection automatically reclaims the memory of objects no longer being used.

Uploaded by

chandana y m
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

Introducing Classes, Objects, and Methods

This document introduces key concepts in object-oriented programming with Java including classes, objects, methods, constructors, and garbage collection. A class defines the form of an object including its data and code. An object is an instance of a class. Methods define reusable blocks of code that operate on an object's data. Constructors initialize an object's data when it is created. Garbage collection automatically reclaims the memory of objects no longer being used.

Uploaded by

chandana y m
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

Introducing Classes, Objects, and

Methods
Class Fundamentals
• 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.
• The methods and variables that constitute a class are
called members of the class. The data members are
also referred to as instance variables.
The General Form of a Class
• Class is created by using the keyword class.
Defining a Class

• A class definition creates a new data type. In this


case, the new data type is called Vehicle.
• To actually create a Vehicle object, you will use a
statement like the following:
Vehicle minivan = new Vehicle();

• After this statement executes, minivan will be an


instance of Vehicle. Thus, it will have “physical” reality.
• Each time you create an instance of a class, you 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 mpg.
• To access these variables, you will use the dot
operator.
• The dot operator links the name of an object with the
name of a member.

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, use the following statement:
• You should call the file that contains this program
VehicleDemo.java because the main( ) method is in
the class called VehicleDemo, not the class called
Vehicle.
• When you compile this program, you will find that two
.class files have been created, one for Vehicle and one
for VehicleDemo.
• The Java compiler automatically puts each class into its
own .class file.
• It is not necessary for both the Vehicle and the
VehicleDemo class to be in the same source file. You
could put each class in its own file, called Vehicle.java
and VehicleDemo.java.
• minivan’s data is completely separate from the data
contained in sportscar.
How Objects Are Created

• 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 a physical copy of the
object and assigns to minivan a reference to that
object. This is done by using the new operator.
• The two steps combined in the preceding statement
can be rewritten like this to show each step
individually:

• 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.
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.
• 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.
For example, after the assignment

executes, both of these println( ) statements

display the same value: 26.


Methods
• A method contains one or more statements. 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 your
program.
• Also, don’t use Java’s keywords for method names.
The general form of a method is shown here:

• ret-type specifies the type of data returned by the


method.
• If the method does not return a value, its return type
must be void.
• The name of the method is specified by name.
• 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.
Adding a Method to the Vehicle Class
Returning from a Method
• In general, there are two conditions that cause a
method to return—first, 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 and one for returning values.
• In a void method, you can cause the immediate
termination of a method by using this form of
return;
• When this statement executes, program control
returns to the caller, skipping any remaining code in
the method.
Returning a Value
• 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.
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.
A method can have more than one parameter. Simply
declare each parameter, separating one from the next
with a comma.
Adding a Parameterized Method to Vehicle
Constructors
• In the preceding examples, the instance variables of
each Vehicle object had to be set manually using a
sequence of statements, such as:
• 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.
• All classes have constructors, whether you define one
or not, because Java automatically provides a default
constructor that initializes all member variables to
their default values, which are zero, null, and false,
for numeric types, reference types, and booleans,
respectively.
• However, once you define your own constructor, the
default constructor is no longer used.
In this example, the constructor for MyClass is

This constructor 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

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. Thus, the output from
the program is
Parameterized Constructors
• 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.
Adding a Constructor to the Vehicle Class
The new Operator Revisited
The general form of new operator :

class-var = new class-name(arg-list);


• 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.
• 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.
Garbage Collection
• 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.
The finalize( ) Method
• It is possible to define a method that will be called
just before an object’s final destruction by the
garbage collector. This method is called finalize( ),
and it can be used to ensure that an object terminates
cleanly.
• To add a finalizer to a class, simply define the
finalize( ) method.
• The Java run-time system calls that method
whenever it is about to recycle an object of that class.
• Inside the finalize( ) method, you will specify those
actions that must be performed before an object is
destroyed.
The finalize( ) method has this general form:

• The keyword protected is a specifier that limits access to


finalize( ).
• It is important to understand that finalize( ) is called just
before garbage collection.
The this Keyword
• The this keyword refers to the current object in a
method or constructor.
• The most common use of the this keyword is to
eliminate the confusion between class attributes and
parameters with the same name .
• this can also be used to:
• Invoke current class constructor
• Invoke current class method
• Return the current class object
• Pass an argument in the method call
• Pass an argument in the constructor call
Pwr class written using the this reference:
• The Java syntax permits the name of a parameter or
a local variable to be the same as the name of an
instance variable.
• When this happens, the local name hides the
instance variable. You can gain access to the hidden
instance variable by referring to it through this.
More Data Types and Operators
Arrays
• An array is a collection of variables of the same type,
referred to by a common name.
• In Java, arrays can have one or more dimensions.
• The principal advantage of an array is that it
organizes data in such a way that it can be easily
manipulated.
• Although arrays in Java can be used just like arrays in
other programming languages, they have one special
attribute: they are implemented as objects.
One-Dimensional Arrays
• A one-dimensional array is a list of related variables.
type array-name[ ] = new type[size];

• type declares the element type of the array. The element


type determines the data type of each element contained
in the array.
• The number of elements that the array will hold is
determined by size.
• Since arrays are implemented as objects, the creation of
an array is a two-step process.
• First, you declare an array reference variable.
• Second, you allocate memory for the array, assigning a
reference to that memory to the array variable. Thus,
arrays in Java are dynamically allocated using the new
operator.
• The following creates an int array of 10 elements and
links it to an array reference variable named sample:

• it is possible to break the preceding declaration in


two,
The output from the program is shown here:

Conceptually, the sample array looks like this:


The general form for initializing a one-dimensional array is shown here:
type array-name[ ] = { val1, val2, val3, …, valN };
Multidimensional Arrays
Two-Dimensional Arrays
• A two-dimensional array is a list of one-dimensional
arrays.
• To declare a two-dimensional integer array table of
size 10, 20 you would write
Irregular Arrays
• When you allocate memory for a
multidimensional array, you need to specify
only the memory for the first (leftmost)
dimension. You can allocate the remaining
dimensions separately.
• assume you are writing a program that stores
the number of passengers that ride an airport
shuttle. If the shuttle runs 10 times a day
during the week and twice a day on Saturday
and Sunday, you could use the riders array
shown in the following program to store the
information. Notice that the length of the
second dimension for the first five indices is
10 and the length of the second dimension for
the last two indices is 2.
Arrays of Three or More Dimensions
• Java allows arrays with more than two dimensions.
• Here is the general form of a multidimensional array
declaration:

type name[ ][ ]…[ ] = new type[size1][size2]…[sizeN];

• For example, the following declaration creates a 4 × 10


× 3 three-dimensional integer array.
Initializing Multidimensional Arrays
• A multidimensional array can be initialized by
enclosing each dimension’s initializer list within its
own set of curly braces.

• val indicates an initialization value. Each inner block


designates a row.
• Within each row, the first value will be stored in the
first position of the subarray, the second value in the
second position, and so on.
Alternative Array Declaration Syntax
T
type[ ] var-name;
here , the square brackets follow the type specifier, not the name of
the array variable
Assigning Array References
• when you assign one array reference variable
to another, you are simply changing what
object that variable refers to.
• You are not causing a copy of the array to be
made, nor are you causing the contents of one
array to be copied to the other.
Using the length Member
The For-Each Style for Loop
• A for-each loop cycles through a collection of objects, such as
an array, in strictly sequential fashion, from start to finish.
• The general form of the for-each style for is shown here.

for(type itr-var : collection) statement-block

• Here, type specifies the type.


• itr-var specifies the name of an iteration variable that will
receive the elements from a collection, one at a time, from
beginning to end.
• The collection being cycled through is specified by collection.
• With each iteration of the loop, the next element in the
collection is retrieved and stored in itr-var. The loop repeats
until all elements in the collection have been obtained.
Although the for-each for loop iterates until all elements
in an array have been examined, it is possible to
terminate the loop early by using a break statement.
There is one important point to understand about the for-each
style for loop. Its iteration variable is “read-only” as it relates to
the underlying array. An assignment to the iteration variable has
no effect on the underlying array.
Iterating Over Multidimensional Arrays
Strings
In many other programming languages, a string is an array of
characters. In Java, strings are objects.

the string "In Java, strings are objects." is automatically made into a
String object by Java.
Constructing Strings
Operating on Strings
Returns true if the invoking string
contains the same character sequence
Boolean equals(str) as str.

int length( ) Obtains the length of a string.


char charAt(index) Obtains the character at the index
specified by index.
int compareTo(str) boolean Returns less than zero if the invoking
string is less than str, greater than zero
equals(str)
if the invoking string is greater than
str, and zero if the strings are equal.

int indexOf(str) Searches the invoking string for the


substring specified by str. Returns the
index of the first match or –1 on failure.
int lastIndexOf(str) Searches the invoking string for the
substring specified by str. Returns the
index of the last match or –1 on failure.
Strings Are Immutable
• The contents of a String object are immutable. That is,
once created, the character sequence that makes up the
string cannot be altered.
• The substring( ) method returns a new string that contains
a specified portion of the invoking string. Because a new
String object is manufactured that contains the substring,
the original string is unaltered, and the rule of
immutability remains intact.
• The form of substring( ) that we will be using is shown
here:
String substring(int startIndex, int endIndex)
• Here, startIndex specifies the beginning index, and
endIndex specifies the stopping point.
The Bitwise Operators
• The bitwise operators can be used on values of type
long, int, short, char, or byte.
• Bitwise operations cannot be used on boolean, float,
or double, or class types.
• They are called the bitwise operators because they
are used to test, set, or shift the individual bits that
make up a value.
Program to convert lower case to uppercase
using bitwise AND
Program to convert upper case to lower
case using bitwise OR
Program to display bits within a byte
The Shift Operators

You might also like