JAVA- Classes and objects

All the functions are performed in the java with the help of classes and objects. Thus java is called a true object oriented programming language.

 Class

A class is encapsulates the data and functions and in java data is called as fields and the functions are called as methods. And the classes are accessed with the help of objects.

Format of a class

class class-name

{

declarations of variables

declarations of methods

}

Class name: Here in above syntax the ‘class’ is a keyword in java. Class name can be any valid name except from the keywords.

Instance-variables: Then we can declare instance-variables. We can declare instance-variables more than 1 as required in program.

e.g:      int  num;

Then these instance-variables can be accessed by the objects only with the help of methods.

One thing is more important that at the end of class we don’t require semi-colon after the closed parentheses where it is must in c++.

Objects

Objects are used to access the class members. The creation of an object is simple and this process is known as instantiating an object. And to create an object we have the ‘new’ operator.

Syntax:            class-name  object-name;

Object-name = new class-name();

In the first line we are just declaring an object. And in the next line we are instantiating it with the new operator.

And class is not occupied any space in memory. But the objects after instantiating take space in memory according to the type and number of instance variables.

e.g:      student  obj;

obj = new  student();

 How to access class members

Leave a Reply

Your email address will not be published. Required fields are marked *