Creating and using class
- A class is a user defined data type.
- Once the class has been defined, we can create “variables” of that type using declarations that are similar to the basic type declarations.
- In java, these variables are termed as instances of classes, which are the actual objects.
- The syntax of class definition is as follow:
class class name[extends superclassname]
{
[fields declaration; ]
[methods declaration; ]
}
- Everything inside the square bracket is optional.
- Classname and superclassname are valid java identifier.
- The keyword extends indicates that the properties of superclass is extended.
Examle:
Class rect
{
int length;
int width;
void getdata(int x,int y)
{
length=x;
width=y;
}
int rectarea()
{
int area=length*width;
return(area);
}
}
Creating Objects
- An object in java is essentially a block of memory that contains space to store the instance variables.
- It is also known as instantiating an object.
Example:
rectangle r1; //declare the object
r1=new rectangle();//initiate the object
- The first statement declares a variable to hold the object reference and second one actually assign the objects reference to the variable.
- We can also combine both statement.
rectangle r1=new rectangle();
No comments:
Post a Comment