Java Programming-Unit II
Java Programming-Unit II
Defining Class
A class is a user-defined data type with a template.
Class definition:
class class-name [extends super-class-name]
{
[Fields declaration;]
[Methods declaration;]
}
Everything inside square brackets – optional.
class empty
{
} \\ Do nothing class
class-name & super-class-name – valid Java identifiers.
Keyword „extends‟ – super class inherits the properties of class name.
Fields Declaration
Data fields (called, instance variables), are placed inside the body of class definition.
Example: double length;
double breadth;
They are instance variables, because they are created whenever an object of the class is
instantiated.
Methods Declaration
General Form:
type method-name (parameter list)
{
method-body;
}
Example:
room(double x, double y)
{
length=x;
breadth=y;
}
Four Parts:
1. Method Name – valid identifier
Example: room ( )
2. Method Type – return type of method. It could be void or data type.
3. Parameter list – list of variable names and types of all input values separated by commas.
Creating Objects
General Form:
class-name object-name = new class-name ( )
Creating an object referred as instantiating an object.
Objects are created using „new‟ operator.
The „new‟ operator creates an object of the specified class and returns a reference to object.
Example: room room1=new room ( );
object-name. method-name(parameter-list);
Class members are accessed using the concerned object and dot operator.
Object name – name of the object.
variable name – instance variable we wish to access.
method-name – method we wish to call.
parameter-list – actual values separated by comma. They must match in number and type of
method-name declared in class.
Example:
room1.area();
room1.length = 15;
II. CONSTRUCTORS
Constructors, special type of method that enables an object to initialize itself when it I created.
Constructors have the same name as the class itself.
They do not specify return type, not even void.
Parameterized Constructor – at the time of object instantiation, the constructor is explicitly
invoked by passing arguments.
Example:
room(double x, double y)
{
length=x;
breadth=y;
}
Default Constructor – does not take any parametric values.
Example:
room ( )
{
}
Output: B = 10