March 19, 2020

Classes and Objects in Java – Fundamentals of OOPs

Java is an object-oriented programming language. You should be familiar with Class and Object in Java to design your code. Java classes and objects are fundamental concepts. Here, classes are user-defined datatypes and objects are an instance of a class.

There are many things which you don’t know about Java Classes and Objects. Let’s learn them together!

Class and Object in Java

Java Classes are user-defined data type from which the objects are created.

Java Objects are the basic entity, they are linked by classes and methods.

To get in-Depth knowledge on Java you can enroll for a live demo on core Java Online Training

1. Java Class

A class is a blueprint or we can say it is a user-defined datatype in which we can specify member functions and declare member variables. These variables in Java are known as ‘instances’ of classes which actually are the ‘objects’.

The components of the Java class declaration are-

  • Class Modifiers – We can access java classes using public, private, protected and default modifiers.
  • Class Name – The class name in java should begin with a capital letter without any spaces.
  • Superclass – The name of the parent of the class is a superclass and its child is a subclass, it should be preceded by the extends keyword. A class can only extend to one parent.
  • Interface Class – Interfaces are implemented by the class, they are separated by commas and are implemented by their keywords.
  • Body Class – The body of a java class is in the curly braces {}.

There are various types of classes in java like nested classes, lambda classes, and anonymous classes. Java Constructors are used to initializing any object in the class. The behaviour of the class is defined by the methods.

Take your career to new heights of success with Java Online Training

2. Java Object

A program can have as many objects as it requires, objects in Java are real-life entities which interacts through methods. Classes are just a prototype but object physically exists, a Java object consists of-

  • State – A state represents the properties of an object and is defined by its attributes.
  • Behavior – The behavior of an object represents the response of an object with other objects, it is defined by the method.
  • Identity – An identity enables one object to interact with another object, it gives a unique name to the Java object.

Example of Java object is – Dog

3. Instantiating a Class in Java

Instantiating a class can also be called a declaration of an object in Java. When an object is created, it is known as instantiating of class. All the instances share common attributes and behavior of the class but the state for every object is different.

To learn more about Classes and Objects inJava and other great features of Java, you can enroll for a live demo on core java training

A class can have any number of objects or instances. For example

Here, the name of the class is a dog, the various objects are Dog 1, Dog 2, Dog 3 and Dog 4 who share the common attributes and behaviour.

3.1 Initializing an Object in Java

Initializing is done by a java constructor, memory is allocated and a reference is given to that memory.

// Class Declaration
public class Dog
   {
// Instance Variables
      String name;
      String breed;
      int age;
      String color;
// Constructor Declaration of Class
         public Dog(String name, String breed,
         int age, String color)
                     {
                this.name = name;
                this.breed = breed;
                this.age = age;
                this.color = color;
            }
// method 1
      public String getName()
    {
        return name;
     }
// method 2
      public String getBreed()
    {
        return breed;
    }
// method 3
      public int getAge()
    {
        return age;
 }
// method 4
      public String getColor()
       {
            return color;
       }
@Override
      public String toString()
       {
            return("Hi my name is "+ this.getName()+
            ".\nMy breed,age and color are " +
            this.getBreed()+"," + this.getAge()+
            ","+ this.getColor());
      }
public static void main(String[] args)
      {
            Dog tuffy = new Dog("shadow","german shephard", 2, "golden");
            System.out.println(tuffy.toString());
      }
 }

Output

3.2 How to Create an Object of a Class in Java?

There are basically 4 ways to create an object in Java, they are-

  • Using a new keyword

It is the most common method to create a Java object.

Example

// creating object of class example
Example obj = new Example();
  • Using Class.forName(String className)

This method is a pre-defined class in java.lang with the name class. It returns the Class object with a string name.

Example

Example obj = (Example)Class.forName("com.p1.Test").newInstance();
  • Using the Clone method in Java

This method returns the copy of the object.

Example

// creating object of class Test
Example obj = new Example();
// creating clone of above object
Example obj1 = (Example)obj.clone();
  • Deserialization

Deserialization is just the reverse of serialization in which we use the byte stream to convert into the original state of a Java object.

Example

FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);
Object obj = in.readObject();

3.3 Creating multiple objects by one type only

  • We need different objects in different methods of a class, and saving different variables for them is not a good practice so we declare a static variable, this saves a lot of memory.

Example

ClassName1 obj = new ClassName1(),
obj2 = new ClassName1();

A parent class reference can use to declare or store a subclass object, this helps in switching into different subclass objects using the same reference variable.

Example

package JavaClassAndObject;
class DataFlair
{
  void courses()
  {
    System.out.println("Number of courses in DataFlair are 9");
  }
  void tutorials()
  {
    System.out.println("Number of tutorials in DataFlair are 35");
  }
}
public class DataFlairCourses
{
  public static void main(String args[])
  {
  DataFlair courseObject=new DataFlair(),tutorialsObject=new DataFlair();
  courseObject.courses();
  tutorialsObject.tutorials();
      
  }
}

Output

4. Anonymous Objects in Java

Anonymous objects are initialized but never stored in a reference variable. These types of objects are used for immediate calling and destroyed after use. They are widely used in different libraries, for example in AWT libraries.

Get More Info On java certification course

Example

btn.setOnAction(new EventHandler()
    {
        public void handle(ActionEvent event)
            {
                System.out.println("Hello World!");
            }
    };

Here btn is the anonymous object to call EventHandler in java.

Summary

By the end of this article, we can say that classes and objects are the building blocks of a Java program. You should master these concepts no matter what programming language you are learning.

Now, you know how to create and declare Java class and instantiate an object with the help of the above example. Hope, you liked our explanation on Classes and Objects in Java.