class in Java

class in Java

exploreJava logo

A class is a major logical construct of Java programs. The class defines the shape and nature of the object. Any program or concept to be developed must be written (encapsulated) within the class.

In some of the programs, classes are created only to encapsulate main() method and to demonstrate the basics of the Java syntax. Class defines a new data type, a user-defined data type. Once a class is defined, it can be used to create objects of that type. A class is a template for an object, object is an instance of the class; words object and instance are used interchangeably.

A class is defined by specifying form and nature of the class. It is done by specifying the data and the code which operates on that data. A class may contain only data, but most of the real-world classes contain both data and the code.

Keyword class (lower case) is used to create a class. The data or variables defined inside class are called instance variables and codes are defined inside methods. But both data and methods are called members of the class. The methods define how the data is used. A general syntax for create a class is as follows:

class classname{
data_type instance-variable1;
data_type instance-variable2;
data_type instance-variable3;
return_type methodname1(parameter-list){
//method body
}
return_type methodname2(parameter-list){
//method body
}
}

Several objects from a class can be created. Each object will have its own copy of the member variables, each occupy its own separate memory space. Data of one object is different and unique from other objects of the same class. Data type of data in the class can be primitive, Java Collections, or user-defined. The member variables can be specified as: private, public, or protected.

All the methods of the class will have same general form: access-specifier, return type, name of method, parameter-list, method body. Access-specifier, return type and parameters depend on the nature of the method.

A simple class

class person{
int id;
String name;
String gender;
}

This is a simple class which name is person. It has three instance variables: id, name, and gender. It is just a template for an object, it does not create any object; no object of class person comes to existence with this declaration.

To create an object of class person, we have to use following statement:

person p = new person();

As this statement is executed, an object p is created and it will have a physical existence, that is it occupies memory space. Any number of instances of class person can be created and each instance will have its own copy of member variables that is each person object will have its own copies of instance variables id, name and gender.

new operator

The new operator is used to allocate memory for an object, it dynamically allocates memory. The general form of new operator is:

class-var = new classname();

Here, class-var is a variable of the class type. The classname is the name of the class that is being instantiated. The classname is followed by parenthesis and it specifies the constructor for the class. A constructor defines the steps when an object of a class is created. Most of the real-world classes have their own constructors within the class definition. If a class has not explicit constructor defined then Java will automatically provide a default constructor. The new operator is used only for creating objects but not for primitive types like int, char. The new operator allocates memory for object during runtime; program can have as many or as few objects as it needs during the execution of the program.

The member variables of the objects are accessed using dot (.) operator. The dot operator associates the object with its members.

p.id = 100;

p.name = "Dinesh";

p.gender = "Male";

These assignments assign values to the member variable of the object p.

class person{
int id;
String name;
String gender;
}
class person_demo{
public static void main(String[] param){
person p = new person();
p.id = 7707;
p.name = "Sabina";
p.gender = "Female";
System.out.println("ID: "+p.id+"\nName: "+p.name+"\nGender: "+p.gender);
}
}

Name of this program must be person_demo as main() method is defined inside it. This program person_demo is compiled using javac compiler. After successful compiling of this program, two class files: person.class and person_demo.class will be created. To run this program person_demo.class should be executed using java interpreter. After executing the program person_demo, the output will be as follows:

A class is defined to create new data type and is used to create objects. The class defines logical framework defining the relationship between its members (variables and methods). Declaring an object of a class is creating instance of the class and object is a logical construct of the class, object allocates space in memory.

Output

ID: 7707
Name: Sabina
Gender: Female

Object Reference variables

person p = new person();
person p1 = p ;

Here, both p1 and p will refer to the same object. Assigning p to p1 don't allocate any memory, it simply makes p1 refer to the same object as p does. Any changes made to object through p1 affect the object to which p is referring. If object p is set to null p1 will still point to the original object.

class person{
int id;
String name;
String gender;
}
class person_demo_II{
public static void main(String[] param){
person p = new person();
p.id = 7707;
p.name = "Sabina";
p.gender = "Female";
System.out.println("For Object P :\n ID: "+p.id+"\nName: "+p.name+"\nGender: "+p.gender);
person p1 = p;
System.out.println("For Object P1 :\nID: "+p1.id+"\nName: "+p1.name+"\nGender: "+p1.gender);
p1.name = "Laxmi";
System.out.println("After making change to p1, For Object P :\nID: "+p.id+"\nName: "+p.name+"\nGender: "+p.gender);
System.out.println("For Object P1 :\nID: "+p1.id+"\nName: "+p1.name+"\nGender: "+p1.gender);
p = null;
System.out.println("After assigning p null, For Object P1 :\nID: "+p1.id+"\nName: "+p1.name+"\nGender: "+p1.gender);
}
}

Access Specifier

Access specifiers specify the visibility, accessibility of class, member variables and methods of the classes. There are four types of access specifiers:

  • private: is the strictest type of access specifier, any member variable or method of a class specified as private is not accessible outside that class. A class and interface can't be defined as private.
  • protected: is less strict than private access specifier, any member variable or method declared as protected can be access with the class where that member is defined and within the derived class of the former class. If class A has protected members and A is derived by B then, the protected members of A is accessible within the class B also.
  • default:If no access specifier is specified then the member will be accessible with the package where the class is declared, but not outside that class.
  • public:The public members are accessible within the package where the member is defined and also outside that package.

Examples

Private access specifier (or modifier)

class A{
private int a;
protected int b;
public int c;
int d;
public void set(int a, int b, int c, int d){
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
public void show(){
System.out.println("A: "+a+"\nB: "+b+"\nC: "+c+"\nD: "+d);
}
}
class access_specifiers_Demo{
public static void main(String [] para){
A a1 = new A();
a1.set(3,4,56,11);
a1.show();
a1.c = 454;
a1.d = 567;
//a1.a = 444; error: a has private access in A
a1.b = 666;
a1.show();
}
}

Methods

A class definition has generally two parts: member variables and methods. A method can return value to the calling routine (part) using a return statement; can have parameter list to take values passed as arguments, it is not compulsory for the methods to have parameters. If a method does not return any value, then the return type will be void, void means nothing. The parameter list of the method is followed by the body of the method where code is written to perform specific tasks. The variables passed as parameters are local to the method, they are not visible in other methods of same the class even, only the class variables are visible within the class body. The general syntax of method is:

type name_of_method(parameter-list){
//body of the method
}

An Example

class circle{
int radius;
double area;
public void setRadius(int r){
radius = r;
}
public double getArea(){
return Math.PI * radius * radius;
}
}
class circle_demo{
public static void main(String[] para){
circle c = new circle();
c.setRadius(4);
System.out.println("Area: "+c.getArea());
}
}

Constructor

A constructor is a method which name is same as the name of the class. It is used to initialize the variables in a class. It instantiates an object immediately upon creation. The constructor is called automatically when an object is created and before the new operator completes. Constructor does not return any thing and has not return type, not even void. Constructors can take parameters.

class circle{
int radius;
double area;
public circle(){
radius = 5;
}
public void setRadius(int r){
radius = r;
}
public double getArea(){
return Math.PI * radius * radius;
}
}
class circle_demo_III{
public static void main(String[] para){
circle c = new circle();
c.setRadius(4);
System.out.println("Area: "+c.getArea());
circle cc =new circle();
System.out.println("Area: "+cc.getArea());
}
}

In the code above, a class circle is defined, it has a constructor, methods to set radius of circle and to get area of the circle. If the setRadius method is not called by an object, then the value of radius will be 5 as the radius is set in the contractor method and calculates area of the circle with radius equal to 5. If setRadius method is called then the value of radius will be set with new value passed as parameter, 5 will be overridden. In the above example two objects of circle class are created: c and cc. Object c has radius of 4 as setRadius is called with 4; object cc has radius of 5 which is set in the constructor (circle()), no setRadius is called for cc.

this keyword

Keyword this is used to refer to the object that invoked the method. can be used inside any method of the current object.

class triangle{
int height;
int base;
double area;
public triangle(int height, int base){
this.height = height;
this.base = base;
}
public double getArea(){
area = 0.5*this.height * this.base;
return area;
}
}
class person_demo{
public static void main(String[] para){
triangle t = new triangle(3,4);
double area_triangle = t.getArea();
System.out.println("Area: "+area_triangle);
}
}

In the above program, method triangle() is constructor, it takes two parameters. Inside the constructor operator this refers to object t of triangle as t calls the constructor; also, in getArea() method, this refers to object.



Inheritance in Java

Loops in Java

Post a Comment

Previous Post Next Post