JAVA 6 Introducing Classes
JAVA 6 Introducing Classes
Outline
• basic elements of a class
• how a class can be used to create objects
• methods,
• constructors, and
• the this keyword
Class
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
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
// 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