Home » Guides Advanced Article

What is a Java Class

Page Visited Visited: 877
Not rated
Rate:

Techs Crunch
June 15, 2016


Techs Crunch
Techs Crunch has written 1 articles for JavaScriptSearch.
View all articles by Techs Crunch...

Class is a structure having variables and method. It is similar to a struct in C. struct in C has only variables. A class can have variables as well as methods.

struct Student{

 int roll_no;

}

Public class Student{

 int roll_no;

 int getRollNumber(){

   return roll_no;

 }

}

As you can see a class has a variable roll_no and a method getRollNumber.

A class is not physically present in memory. It is just a blue print.

A Object is an instance of the class. Multiple objects can be created from a class.

Consider the above image the steel star shaped cookie cutter is a class. We can use it to create actual cookies, Multiple cookies.

Similarly Student above is a class.

When we do

Student s = new Student();

We create an object/instance of the class.

A class has many advantages over a struct.

Abstraction

The methods inside a class have access to the variables in a class. This gives a controlled access to the variables of a class. Consider this:

Student s = new Student();

s.roll_no= -2;

Here we are setting the variable roll_no to a negative value. Which is logical wrong. But since the roll_no is accessible outside the class anybody can change it. Consider this now:

Public class Student{

 private int roll_no;

 public int getRollNumber(){

   return roll_no;

 }

 public void setRollNumber(int var){

if(var>0){

roll_no=var;

}

 }

We have made the variable roll_no as private. So now it can not be accessed from outside the class. We have added a public method setRollNumber to set the roll_no. In here we only set roll_no if the value passed is greater than 0. This protects our student object from a invalid state.

 

Student s = new Student();

s.setRollNumber(-1);

s.setRollNumber(1);

 

Inheritance

Inheritance in English means having some habits from our ancestors (Parents). Classes can have relationships among each other. A class can be a parent class to another class. In this case a child class inherits methods and variables from the parent class.

Consider below example

Class Animal{

}

Class Dog extends Animal{

}

Here Dog is a child class of Animal. The keyword extends creates this relationship. Dog inherits all the member variables and method of super class.

To understand more of Classes and Objects refer Core Java Interview Questions


Add commentAdd comment (Comments: 0)  

Advertisement

Related Resources

Other Resources

arrow