0% found this document useful (0 votes)
37 views18 pages

Class Fundamentals - Final

Question bank

Uploaded by

shettyironman
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)
37 views18 pages

Class Fundamentals - Final

Question bank

Uploaded by

shettyironman
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/ 18

Department of Computer Science, BCK

Introducing Classes, Objects, and Methods

Class Fundamentals:

Since all Java program activity occurs within a class, we have been using

classes since the start of thisbook. A class is a template that defines the

form of an object. Itspecifies both the data and the code that will operate on

that data. Java uses a class specification toconstruct objects. Objects are

instances of a class. Thus, a class is essentially a set of plans thatspecify 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 existsin memory. Recall that the methods and

variables that constitute a class are called members ofthe class. The data

members are also referred to as instance variables.

The General Form of a Class:


A class is created by using the keyword class. A simplified general form
of a class definition isshown here:

1
Department of Computer Science, BCK

The general form of the class definition is as follows:


class classname [extends superclassname]
{
Variable declaration;
Method declaration;
}
Defining a Class:
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 avehicle: the number
of passengers that it can carry, its fuel capacity, and its average fuel
consumption(in miles per gallon).

2
Department of Computer Science, BCK

How Objects Are Created:


In the preceding programs, the following line was used to declare an
object of type 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 a physical copy of the object and assigns to minivan
areference to that object. This is done by using the new operator.
Reference Variables and Assignment:
In an assignment operation, object reference variables act differently
than do variables of a primitivetype, such as int. When you assign one
primitive-type variable to another, the situation isstraightforward. The variable
on the left receives a copy of the value of the variable on the right.
Whenyou assign one object reference variable to another, the situation
is a bit more complicated becauseyou are changing the object that the
reference variable refers to. The effect of this difference can causesome
counterintuitive results. For example, consider the following fragment:

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 simplymakes 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

3
Department of Computer Science, BCK

Methods:
As explained, instance variables and methods are constituents of classes.
Although data-only classes are perfectly valid, most classes will havemethods.
Methods are subroutines that manipulate the data defined by the class
and, in many cases,provide access to that data. A method contains one or more
statements. In well-written Java code, each method performs onlyone task.
Each method has a name, and it is this name that is used to call the method.
In general, youcan give a method whatever name you please. However,
remember that main( )is reserved for themethod 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:

Here, ret-typespecifies the type of data returned by the method. This can
be any valid type, includingclass types that you create. If the method does not
return a value, its return type must be void.
Thename of the method is specified by name. This can be any legal
identifier other than those alreadyused by other items within the current scope.
The parameter-listis a sequence of type and identifierpairs separated by
commas. Parameters are essentially variables that receive the value of
theargumentspassed to the method when it is called. If the method has no
parameters, the parameter listwill be empty.
Constructors:
A constructor is a special type of method thatinitializes an object
when it is created. It has the same name as its class and issyntactically
similar to a method. However, constructors have no explicit return type.
Typically, youwill use a constructor to give initial values to the instance
variables defined by the class, or to performany other startup procedures
required to create a fully formed object.

4
Department of Computer Science, BCK

All classes have constructors, whether you define one or not, because
Java automatically provides adefault 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
defineyour own constructor, the default constructor is no longer used.

Output:
10 10
Parameterized Constructors:
Parameterized constructor is a constructor that accepts one or more
parameters. Parameters areadded to a constructor in the same way that they
are added to a method: just declare them inside theparentheses after the
constructor’s name. For example, here, MyClassis given a
parameterizedconstructor:

5
Department of Computer Science, BCK

Garbage Collection and Finalizers


As you have seen, objects are dynamically allocated from a pool of free
memory by using the newoperator. As explained, memory is not infinite, and
the free memory can be exhausted. Thus, it ispossible for new to fail because
there is insufficient free memory to create the desired object. For thisreason, a
key component of any dynamic allocation scheme is the recovery of free
memory fromunused objects, making that memory available for subsequent
reallocation. In many programminglanguages, the release of previously
allocated memory is handled manually. For example, in C++, youuse the delete
operator to free memory that was allocated.
However, Java uses a different, moretrouble-free approach: garbage
collection.Java’s garbage collection system reclaims objects automatically—
occurring transparently, behindthe scenes, without any programmer
intervention. It works like this: When no references to an objectexist, that
object is assumed to be no longer needed, and the memory occupied by the
object isreleased. This recycled memory can then be used for a subsequent
allocation.

6
Department of Computer Science, BCK

The finalize( ) Method


It is possible to define a method that will be called just before an object’s
final destruction by thegarbage collector. This method is called finalize( ), and
it can be used to ensure that an objectterminates cleanly. For example, you
might use finalize( )to make sure that an open file owned bythat object is
closed.To add a finalizer to a class, you simply define the finalize( )method.
The Java run-time systemcalls that method whenever it is about to recycle an
object of that class. Inside the finalize( )methodyou will specify those actions
that must be performed before an object is destroyed.
The finalize( )method has this general form:

The this Keyword


When a method is called, it isautomatically passed an implicit argument
that is a reference to the invoking object (that is, the objecton which the
method is called). This reference is called this.
Example: refer class notes.

Controlling Access to Class Members


Java’s Access Modifiers
Member access control is achieved through the use of three access
modifiers: public, private, andprotected. As explained, if no access modifier is
used, the default access setting is assumed. In thischapter we will be
concerned with public and private. The protected modifier applies only
wheninheritance is involved.
 When a member of a class is modified by the public specifier, that
member can be accessed by any other code in your program. This
includes methods defined inside other classes.

7
Department of Computer Science, BCK

 When a member of a class is specified as private, that member can be


accessed only by other members of its class. Thus, methods in other
classes cannot access a private member of another class.
The default access setting (in which no access modifier is used) is the same
as public unless yourprogram is broken down into packages.

8
Department of Computer Science, BCK

Pass Objects to Methods:


Up to this point, the examples in this book have been using simple types
as parameters to methods.However, it is both correct and common to pass
objects to methods. For example, the followingprogram defines a class called
Block that stores the dimensions of a three-dimensional block:

9
Department of Computer Science, BCK

Recursion
The process of calling a method by itself is called recursion, and a
method that calls itself is saidto be recursive. The key component of a
recursive method is a statementthat executes a call to itself. Recursion is a
powerful control mechanism.The classic example of recursion is the
computation of the factorial of a number.

10
Department of Computer Science, BCK

Example:

11
Department of Computer Science, BCK

Understanding static
There will be times when you will want to define a class member that will
be used independently ofany object of that class. Normally a class member
must be accessed through an object of its class, butit is possible to create a
member that can be used by itself, without reference to a specific instance.
Tocreate such a member, precede its declaration with the keyword static.
When a member is declaredstatic, it can be accessed before any objects of its
class are created, and without reference to anyobject. You can declare both
methods and variables to be static. The most common example of astatic
member is main( ). Outside the class, to use a static member, you need only
specify the name of itsclass followed by the dot operator. No object needs to be
created. For example, if you want to assignthe value 10 to a static variable
called count that is part of the Timer class, use this line:

A static method can be called in the same way—by use of the dot
operator onthe name of the class.
Variables declared as static are, essentially, global variables. When an
object is declared, no copyof a static variable is made. Instead, all instances of
the class share the same static variable. Here isan example that shows the
differences between a static variable and an instance variable:

12
Department of Computer Science, BCK

13
Department of Computer Science, BCK

The difference between a static method and a normal method is that the
static method is calledthrough its class name, whereas the normal methods
are called through the objects of the class.
Methods declared as static have several restrictions:
 They can directly call only other static methods.
 They can directly access only static data.
 They do not have a thisreference.

Static Blocks:
Sometimes a class will require some type of initialization before it is
ready to create objects. Forexample, it might need to establish a connection to
a remote site. It also might need to initializecertain static variables before any
of the class’ static methods are used. To handle these types ofsituations Java
allows you to declare a static block. A static block is executed when the
class is first loaded. Thus, it is executed before the class can be used for any
other purpose. Here is an example of astatic block:

14
Department of Computer Science, BCK

Introducing Nested and Inner Classes:


The nested classis a class that is declared within another class.
A nested class does not exist independently of its enclosing class. Thus, the
scope of a nested classis bounded by its outer class. A nested class that is
declared directly within its enclosing class scope isa member of its enclosing
class. It is also possible to declare a nested class that is local to a block.
There are two general types of nested classes:
1. those that are preceded by the static modifier and
2. Those that are not.

15
Department of Computer Science, BCK

The only type that we are concerned about in this book is the non-static
variety.This type of nested class is also called an inner class. It has access to
all of the variables and methodsof its outer class and may refer to them directly
in the same way that other non-staticmembers of theouter class do.
Sometimes an inner class is used to provide a set of services that is used only
by its enclosing class.
Here is an example that uses an inner class to compute various values for its
Varargs: Variable-Length Arguments:
Sometimes you will want to create a method that takes a variable
number of arguments, based on itsprecise usage. To create such a method
implies that there must be some way to create a list of argumentsthat is
variable in length, rather than fixed. In cases where the maximum number of
potential arguments is larger, or unknowable, an approach was used in which
the arguments were put into an array, and then the array waspassed to the
method.
Varargs Basics
A variable-length argument is specified by three periods (...). For
example, here is how to write amethod called vaTest( )that takes a variable
number of arguments:

Notice that v is declared as shown here:

16
Department of Computer Science, BCK

This syntax tells the compiler that vaTest( )can be called with zero or more
arguments. Furthermore,it causes v to be implicitly declared as an array of
type int[ ]. Thus, inside vaTest( ), v is accessedusing the normal array syntax.
Using Command-Line Arguments:
Now that you know about the String class, you can understand the
argsparameter to main( )that hasbeen in every program shown so far. Many
programs accept what are called command-line arguments.
A command-line argument is the parameters supplied to the application
program at the time of invoking it for execution.The command-line arguments
are stored as strings in the String array passed to main( ).
For example, thefollowing program displays all of the command-line
arguments that it is called with:

17
Department of Computer Science, BCK

18

You might also like