Class and Object in Java

Let’s learn about the class and Object in Java. Java is an object-Oriented programming language, In object-oriented programming technique, we design a program using objects and classes.

 

What is Objects in JAVA

Objects have its own behavior and state. The object can be physical and logical. An object is an instance of a class.

If we consider a car, then its state is – name, brand, color, and the behavior is – speed, No of gears, running mode.

Software objects also have state and behavior. A software object’s state is stored in variables and behavior is shown via methods.

So in software development, methods operate on the internal state of an object and the object-to-object communication is done via methods.

 

What is Class in JAVA

A class is a group of objects that has common properties. It is a template or blueprint from which objects are created.

A class is declared using class keyword. A class contains both data and code that operate on that data. The data or variables defined within a class are called instance variables and the code that operates on this data is known as methods.

Rules for the Java Class

  • A class can have only public or default access specifier.
  • The class must have Class keyword.
  • The class variables and methods should be declared within the class body, in curly braces {}.
  • Each .java source file may contain only one public class.
  •  The source file name must match the public class name and it must have a .java suffix.

Example of class and Object

We have created a Car class that has two data members brand and name. We are creating the object of the car class by new keyword(new keyword is used to create the object of the class) and printing the objects value.

Here the new keyword creates an actual physical copy of the object and assigns it to the “c” variable. It will have physical existence and get memory in heap area. The new operator dynamically allocates memory for an object.

 

Other ways to create Object in Java

There are many ways tp create the object in Java like –

  • By new Keyword
  • By newInstance() method
  • By clone() method
  • By factory method

 

Anonymous object:

Whenever an object is instantiated but is not assigned to a reference variable, it is called anonymous object instantiation.
Simple object instantiation:
Sample  s = new Sample();

Anonymous object instantiation:
new Sample();

The anonymous object is created and dies instantaneously. The anonymous object can be used only once in the program.  We can’t use twice or more.

Let’s see the use of Anonymous Object using this factorial Program.

package Com.EasyBix.CoreJava;

 

Selenium Video Tutorial:

If you liked this video, then please subscribe to our YouTube Channel for more video tutorials.

 

0 Comment

Leave a Reply