What are the Class and Objects in Java and How to create a class and objects with Examples?

0
335
how to create classes and objects in java
croe java topics


In this article, we will learn about What are Class and objects, How to create a Class and objects, How many Ways to create objects of a class, How to Initialize Objects, and also learn What are Anonymous objects in the java.

Before going to understand the java programs. everyone needs to know some basic information about Classes and objects. In java Classes and Objects are simple and basic concepts of Object Orientation. Which resolves the real-world related Problems.

What are the Class in Java?

Class is a user-defined blueprint or a template, or a master copy of java Programs. using that we can create any number of objects.

In other words, we can’t write a program without class. As well as we can’t create an Object, because objects are always present in the class. If we haven’t any class then objects can not exist without class.

  • The class is a logical entity.
  • Multiple Objects created using the same class are called Similar Object or Identical Object.
  • Every Object works independently. if a single Object is destroyed then It Doesn’t affect Just another Object.

Here are Some components, using these we can declare a class:-

  1. Modifiers: A class could be public or it can be default access.
  2. Name of Class: Class name must start with a first capital letter else it will be counted in camel case.
  3. Superclass(if any): this is used in case of inheritance (is called superclass or parent class). if have any, preceded with the keyword called extends.
  4. Interfaces(if have any): preceded by the keyword called implements. Note:- every class can implement more than one interface.
  5. Body Of a class: Your class body is surrounded by open and close braces { }.

Identification Rules Of Class.

there is a list of some rules before declaring a class. We need to remember these rules.

  • Every time you must start a class name with a capital letter and avoid the camel case ex:- Hello_World NOT helloworld.
  • No space should be there in between in class name, variable name, and also method name.
  • Also, no special character except ($ and _ ) if needed.
  • We can not start any class name, variable name, and method name with numerics.
  • You can’t use any java keywords as a class name, variable name, or method name. (Java keywords like:- class, interface, abstract, import, package, static, public, private, etc…)

How to create a Class?

According to the rules we are creating a class with the help of a keyword called “class”. This is the basic Syntax of a class.

class named “Test” with a variable a :

public class Test {
  int t = 10;
}
Class Explanation in Java

What is the Object in java?

real world objects

An object is a Real-world Physical entity. Anything which has Physical presence can be considered as an Object. Without the class, objects can not be created. It is a basic unit of any program and we can create any number of objects in a class.

Note:- After the Successful compilation process, the compiler-generated a default Constructor. Where the constructor name and class name must be the same.

Objects are contain 2 important things.

1.State: it always represents property or information or features of an object. (technical Ex: Variables)
Real-world Ex:- we have a Mobile.

  • color of a mobile
  • the price of the mobile.

these two specification of a mobile is called states of a mobile object.

states of a mobile object

2.Behavior: it always represents the action performed by an object. (technical Ex: Methods)
Real-world Ex:- calling and texting is the behavior of the mobile object.

behavior of a mobile object in java

these are the basic characteristics of a object.

Some important things of Object.

Before creating an object in a class, you should need to remember these things.

  • The class name and object name must be the same.
  • We can create unlimited objects in the class with the help of a “new” keyword.
  • In java, Objects are stored in Heap Memory. Memory allocation & Memory deallocation i.e, complete Memory management is taken care of by JVM.
  • Inside the heap memory, the object contains the object name and address ( in HexaDecimal format .).
  • The address is stated in a variable called reference variable. Which helps to access the data present in the object.
  • Jvm creates an object in heap Memory when we call the Constructor using a new Keyword.

How to Create an Object in the Class?

Java have many different methods to create objects. But we are using a common method to create objects in java.

So now we already created a class (class name). Now we can create an object in the class. This is the basic syntax to create an object.

Basic Syntax of Object creation:-

public class Test {
  int a = 10;

  public static void main(String[] args) { //Main method.
    Test Obj = new Test();  //Creating a Object with the help of "new" keyword and "Obj" is a referance of this object.
    System.out.println(Obj.a); //printing result with println method.
  }
}

create multiple object of one class?

For Ex:-

public class Test {
  int a = 10;
  int b = 20;

  public static void main(String[] args) { //Main method.
    Test Obj1 = new Test();  //Creating an Object with the help of "new" keyword and "Obj" is a reference of this object.
    Test Obj2 = new Test();
    System.out.println(Obj1.a); //printing result with println method.
    System.out.println(Obj2.a);
  }
}

Different Ways to create objects of a class in java:-

In Java there are many different ways to create objects.

1.We can create objects Using a new keyword.
This is the general method to create objects, for example:-

// creating object of class Demo with new Keyword.
Demo Obj = new Demo();

2. Using the class.forName(String className) method.
This is an already predefined class in the java.lang package of java with the name Class.

// consider class Test present in com.p package
Demo obj = (Demo)Class.forName("com.p.Demo").newInstance();

3. Using the clone method.
The clone method exists in Object class.using this method it will create a clone of the object and return a copy of the object.

//creating object of class Demo with new Keyword.
Demo d1 = new Demo();

// making clone of above object
Demo d2 = (Demo)d1.clone();

4. By using Deserialization.
De-serialization is the one more interesting technique of reading an object with the help of reference from the saved state in a file.

Gamefile file = new Gamefile(filename)
Game g= new Game (game);
Game obj = g.readGame();

5. and using factory method.

Direct Initialization of Objects.

we can initialize an object directly with the help of variables. but we can not change the values of objects after initialize directly. the value must be fixed for all the objects in the class.

Now we are creating a “car” class and taking some String variables and initialize the objects through variables.

Public class Car {
   String color="red";
   String name="BMW";
     Car c1 =new Car();
     Car c2 =new Car();
     Car c3 =new Car();
}

Explanation:- here you can see how are the objects are saved in the heap memory with the address. every object has a specific block with an address.

Initialization of Objects in java

Initialize using Object Reference.

There is also a common way to initialize objects using references. with the reference, we can initialize multiple objects with different values.

Now we are creating a class and taking some variables without initialization. and creating three objects in the main method. after creating objects we initialize different values for each object.

Public class Car {
     String color;
     String company_name;
   public static void main(String[] args) {
          Car c1 =new Car(); //object 1
          c1.color="Orange"; // initializing with reference variable
          c1.company_name="BMW";
          Car c2 =new Car();  //object 2
          c2.color="Red";  //initializing with reference variable
          c2.company_name="Ford";
          Car c3 =new Car ();  //object 3
          c2.color="White";  //initializing with reference variable
          c2.company_name="Honda";
  }
}

Explanation:- in the diagram you can see, how’s objects are stored in the heap memory with different address and values.

Initialize using Object Reference in java

Anonymous objects in java?

the objects which are instantiated but they are not stored in the heap memory,  because they have not any reference variable.

in other words, an object which has no reference is called an anonymous object in java. if you want to use any object at once then create an anonymous object is a good practice.

Here is Some important factors of anonymous objects:- 

  • Anonymous objects are used for fast method calling.
  • These types of objects are destroyed after the calling of the method.
  • The scope of these types of objects is wide with different libraries in java. (ex:- AWT libs).

Example:-

public class Demo{  //creating a class.
 void fact(int n){  //crate a "fact" method.
  int ft=1;    // take a veriable which stores the loop values.
  for(int i=1;i<=n;i++){  //using for loop.
   ft=ft*i;  
  }  
 System.out.println("the factorial is= "+ft);  //printing factorial
}  
public static void main(String args[]){  // main method
 new Demo().ft(3);     //anonymous object with calling method.
}  
}  

Output:-

the factorial is= 6

Admin Word:- In this article, I am trying to teach you, What are the class and objects in java, How to create a class and objects, How many Ways to create objects in a class, How to Initialize of objects, and also learn What are Anonymous objects in the java. I hope this will help you to understand classes and objects in the java.

if you have any questions regarding this article please feel free to ask in the comment below of this article.

0 0 votes
Article Rating
croe java topics


Previous articleWhat is Java, Full Introduction of Java for Beginners with Examples?
Next articleWays to Download and Install Java JDK 16 in Windows 10 -[2021]
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments