0% found this document useful (0 votes)
17 views

JAVA 6 Introducing Classes

Uploaded by

kiranchaitanyab
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

JAVA 6 Introducing Classes

Uploaded by

kiranchaitanyab
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 35

Introducing Classes

Outline
• basic elements of a class
• how a class can be used to create objects
• methods,
• constructors, and
• the this keyword
Class

• A basis for the Java language.


• Each concept we wish to describe in Java must
be included inside a class.
• A class defines a new data type, whose values
are objects:
• A class is a template for objects
• An object is an instance of a class
Class Definition

A class contains a name, several variable declarations


(instance variables) and several method declarations. All are
called members of the class.
General form of a class:
class classname {
type instance-variable-1;

type instance-variable-n;
type method-name-1(parameter-list) { … }
type method-name-2(parameter-list) { … }

type method-name-m(parameter-list) { … }
}
Example: Class Usage
class Box {
double width;
double height;
double depth;
}
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
vol = mybox.width * mybox.height * mybox.depth;
System.out.println ("Volume is " + vol);
}
}
class
• Notice that the general form of a class does not specify a
main( ) method.
• Java classes do not need to have a main( ) method.
• You only specify one if that class is the starting point for your
program.
• Further, applets don’t require a main( ) method at all.
Sample Java Program
Declaring Objects
• Obtaining objects of a class is a two-step process.
1. First, you must declare a variable of the class type.
– This variable does not define an object.
– Instead, it is simply a variable that can refer to an object.
2. Second, you must acquire an actual, physical copy
of the object and assign it to that variable.
– You can do this using the new operator.
Declaring Objects
• The new operator dynamically allocates (that
is, allocates at run time) memory for an object
and returns a reference to it.
• This reference is, more or less, the address in
memory of the object allocated by new.
• This reference is then stored in the variable.
Box mybox; // declaring a reference
mybox = new Box(); // allocating a Box object to
the reference ‘mybox’
Declaring Objects
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object
• The first line declares mybox as a reference to an object of type
Box.
• After this line executes, mybox contains the value null, which
indicates that it does not yet point to an actual object.
• Any attempt to use mybox at this point will result in a compile-
time error.
• The next line allocates an actual object and assigns a reference to
it to mybox.
• After the second line executes, you can use mybox as if it were a
Box object.
• But in reality, mybox simply holds the memory address of the
actual Box object.
Declaring Objects
A Closer Look at new
• the new operator dynamically allocates memory for an
object. It has this general form:
class-var = new classname( );
• The class name followed by parentheses specifies the
constructor for the class.
• A constructor defines what occurs when an object of a class is
created.
• Most real-world classes explicitly define their own
constructors within their class definition.
• However, if no explicit constructor is specified, then Java will
automatically supply a default constructor
• It is important to understand that new allocates memory for
an object during run time
Assigning Object to Reference Variables

Box b1 = new Box();


Box b2 = b1;
Assigning Object to Reference Variables
• Although b1 and b2 both refer to the same object, they are
not linked in any other way.
• For example, a subsequent assignment to b1 will simply
unhook b1 from the original object without affecting the
object or affecting b2. For example:
Box b1 = new Box();
Box b2 = b1;
// ...
b1 = null;
• Here, b1 has been set to null, but b2 still points to the original
object.
Methods
General form of a method definition:
type name(parameter-list) {
//method body
… return value;

}
Components:
1) type - type of values returned by the method. If a method
does not return any value, its return type must be void.
2) name is the name of the method
3) parameter-list is a sequence of type-identifier lists
separated by commas
4) return value indicates what value is returned by the
method.
Example: Method
• Classes declare methods to hide their internal data
structures, as well as for their own internal use:
• Within a class, we can refer directly to its member
variables:
class Box {
double width, height, depth;
void volume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
Parameterized Method
• Parameters increase generality and applicability of a
method:
• 1) method without parameters
int square() { return 10*10; }
• 2) method with parameters
int square(int i) { return i*i; }
• Parameter: a variable receiving value at the time the
method is invoked.
• Argument: a value passed to the method when it is
invoked.
Adding a Method That Takes Parameters

int square(int i)
{
return i * i;
}
Constructors
• A constructor initializes an object immediately upon creation.
It has the same name as the class in which it resides and is
syntactically similar to a method.
• Once defined, the constructor is automatically called
immediately after the object is created, before the new
operator completes.
• Constructors have no return type, not even void.
• This is because the implicit return type of a class’ constructor
is the class type itself.
• It is the constructor’s job to initialize the internal state of an
object so that the code creating an instance will have a fully
initialized, usable object immediately.
Parameterized Constructors
Constructor

• A constructor initializes the instance variables of an object.


• It is called immediately after the object is created but before
the new operator completes.
1) it is syntactically similar to a method:
2) it has the same name as the name of its class
3) it is written without return type; the default
return type of a class
• constructor is the same class
• When the class has no constructor, the default constructor
automatically initializes all its instance variables with zero.
Example: Constructor

class Box {
double width;
double height;
double depth;
Box() {
System.out.println("Constructing Box");
width = 10; height = 10; depth = 10;
}
double volume() {
return width * height * depth;
}
}
Parameterized Constructor

class Box {
double width;
double height;
double depth;
Box(double w, double h, double d) {
width = w; height = h; depth = d;
}
double volume()
{ return width * height * depth;
}
}
Access Control: Data Hiding and Encapsulation

• Java provides control over the visibility of variables and


methods.
• Encapsulation, safely sealing data within the capsule of
the class Prevents programmers from relying on details
of class implementation, so you can update without
worry
• Helps in protecting against accidental or wrong usage.
• Keeps code elegant and clean (easier to maintain)
Access Modifiers: Public, Private, Protected
• Public: keyword applied to a class, makes it
available/visible everywhere. Applied to a method or
variable, completely visible.
• Default (No visibility modifier is specified): it behaves
like public in its package and private in other packages.
• Private: fields or methods of a class are only visible
within that class. Private members are not visible
within subclasses, and cannot be inherited.
• Protected: members of a class are visible within the
class, subclasses and also within all classes that are in
the same package as that class.
Keyword this

• Keyword this allows a method to refer to the object


that invoked it.
• It can be used inside any method to refer to the
current object:
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
Keyword this
public class Circle {
private double x,y,r;

// Constructor
public Circle (double x, double y, double r) {
this.x = x;
this.y = y;
this.r = r;
}
//Methods to return circumference and area
public double circumference() { return 2*3.14*r;}
public double area() { return 3.14 * r * r; }
}
Object Destruction

• A program accumulates memory through its


execution.
• Two mechanism to free memory that is no longer
need by the program:
1) manual – done in C/C++
2) automatic – done in Java
• In Java, when an object is no longer accessible
through any variable, it is eventually removed from
the memory by the garbage collector.
• Garbage collector is parts of the Java Run-Time
Environment.
Garbage Collection

• Garbage collection is a mechanism to remove objects from


memory when they are no longer needed.
• Garbage collection is carried out by the garbage collector:
1) The garbage collector keeps track of how many references
an object has.
2) It removes an object from memory when it has no longer
any references.
3) Thereafter, the memory occupied by the object can be
allocated again.
4) The garbage collector invokes the finalize method.
finalize() Method

• A constructor helps to initialize an object just after it


has been created.
• In contrast, the finalize method is invoked just before
the object is destroyed:
• 1) implemented inside a class as:
protected void finalize() { … }
• 2) implemented when the usual way of removing
objects from memory is insufficient, and some
special actions has to be carried out

You might also like