×

Objects and Classes in Java

Objects and Classes in Java

Classes and objects are the basic concepts of object-oriented programming. It revolves around the real world entity. In Java, the object is a physical and logical entity, whereas classes are logical entity only.

Objects in Java-

Objects are real-world entities that have state and behavior. Objects can be physical and logical. It is the instance of the class. Some example of objects are-

table, fan, chair, car, train, etc.

We can say objects are-

  • Real-world entities
  • Instances of the classes
  • Tangible or intangible
  • Entities which have state and behavior

Objects can be tangible or intangible both. The banking system is the example of the intangible object. Object corresponds to things found in the real world.

Every object has some characteristics like its name, method, and other information about it. Characteristics of an object are-

  • State
  • Behavior
  • identity

State- it contains the attribute and value of an object. It is the reflection of object properties.

Behavior- it contains methods of an object. It is the response reflection of an object to another object. It represents the functionality of an object like deposit, etc.

Identity- identity is a unique id. It is used internally by the JVM to identify the uniqueness of the object.

Example of an object

Object Car

Identity- 

Object name- car

Attributes-

Brand

Model

Color

speed

Behavior-

Run

Speed

Object declaration-

As an object is called an instance of the class so, when an object is created in a class, class is said to be instantiated. All the instances share the attributes and properties of the class, but the values of these attributes (state) are unique. A single class can have any number of instances.

Example-

public class Car
{
String brand;
String model;  //instance variable
int speed;
public Car(String brand, String model, int speed)
{
this.brand=brand;
this.model=model;
this.speed=speed;
}
public String getBrand()
{
return brand;
}
public String getModel()
{
return model;
}
public int getSpeed()
{
return speed;
}
public String method()
{
return("my cars brand is" +this.getBrand()+"\n my model is  " +this.getModel()
+ "my speed is " +this.getSpeed());
}
public static void main(String[] args)
{
Car c1=new Car(" toyota", "camery" ,250);
System.out.println(c1.method());
}}

Output-

my cars brand is Toyota
my model is  camery my speed is 250

Ways to create an object of a class-

  • Using a new keyword
  • Using class.forName(String  className) method
  • Using clone() method
  • Deserialization

Using new keyword-

It is most common and used way to create object in java.

Demo obj= new Demo()

Using Class.forName(String className) method-

In JAVA, there is a predefined class Class in java.lang package. The forName() method is a Java Class method. This method returns the class object associated with the class or interfaces with the given name in the parameter as String.

Demo obj=(Demo)Class.forName(“pack1.Demo”).newInstance();

Consider class Demo present in pack1 package.

Using clone() method-

clone() method is an Object class method. This method creates and returns a copy of the object class.

Demo obj=(Demo)obj.clone();

Using Deserialization-

Deserialization is a process of reading an object from a saved file.

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

Classes in java-

Classes are the user-defined blueprint of objects. It contains a set of properties and method that are common to all objects of one type.

We use the keyword class for creating a class.

Syntax-

class ClassName
{
Methods
Fields
…….
…….
}

A Java class contains-

  • Methods
  • Fields
  • Constructors
  • Blocks
  • Nested classes and interfaces

Methods in Java-

In Java, a method is a block of code meant for any certain operation. It runs when it calls. Methods can be called anywhere in the program. Methods are like functions.

Advantages-

Code re-usability is the main advantage of methods we can use the code many times by defining only once.

Code optimization is also an advantage of methods. We can reduce the line of code of a program by defining methods.

To create a method-

Methods should be defined within the class. It should be determined by method name followed by parenthesis (). There are some predefined methods in java, like System.out.println(). An example of creating method is below.

public class Demo{
  static void method1() {
    // code to be executed
  }
}

In the given example we have defined method ‘method1’ within the demo class.

To call a method-

To call a method write method name followed by parenthesis () and thereafter semicolon ‘; ‘.  Like in the below program, I defined method1 for printing “in method 1”. When I will call the method1() it will give the output as “in method 1”.

public class Demo{
  static void method1() {
    System.out.println("in method 1");
  }
public static void main(String[] args) {
    method1();
  }
}

Output-

In method 1

Fields-

A class field may contain many things like variables constant and other data types.

A class contains any of the following variables-

  • Local variables
  • Class variable
  • Instance variable

Local variable-

Local variables are defined within the methods, constructor, or blocks. These variables are initialized within the block and destroyed when the method is completed. 

Class variable-

Class variables are defined within the class outside any methods with the static keyword.

Instance variable-

An instance variable is defined within the class outside any methods. These variables are initialized when the class is initialized. Instance variable can be accessed anywhere in the program.

Constructors-

One of the most important subtopics of the class is a constructor. Every class contains a minimum of one constructor. If we do not define it manually, then Java compiler will create a constructor by default.

When a new object is initialized, a constructor is invoked. It initializes the objects. Its name is as class name. More than one constructor can be created in a single class.

Let's have a look at the below example-

public class  Student
{
public Student()
{
…….// initializing objects
…….
}}

Block in Java-

A block contains one or more statements enclosed in braces. Generally, a block is used to group several statements so that they can be used on the requirement.

Below is an example of a simple block.

{ //block start
        int a = 50;
        a++;
} //block end

Java example for objects and classes-

Example1-

This is a simple example for how to define class and fields.

class Shop{ 
//fields 
float mrp;/instance variable 
String name; 
//main method 
public static void main(String args[]){  
  Shop s1=new Shop();//creating an object of Shop 
  //Printing values
  System.out.println(s1.mrp);//accessing member variable
  System.out.println(s1.name); 
} 
}

Output-

0.0
null

Example2-

For initialization through reference variable-

Initialization means storing the data into a variable. In this example, we will store the value into an object through the reference variable.

class Shop1{ 
int mrp; 
String name; 
public static void main(String args[]){ 
  Shop1 s1=new Shop1(); 
  s1.mrp=24575; 
  s1.name="Samsung LED"; 
  System.out.println(s1.mrp+" "+s1.name);
} 
}

Output-

24575 Samsung LED

Example3-

Initialization through method-

In this example, we will create two objects of the Shop class and initializing the value of these objects through methods.

class Shop2{ 
float mrp; 
String name; 
void record(int m, String n){ 
  mrp=m; 
  name=n; 
} 
void display(){System.out.println(mrp+" "+name);} 
public static void main(String args[]){ 
  Shop2 s1=new Shop2(); 
  Shop2 s2=new Shop2(); 
  s1.record(24575,"Samsung LED"); 
  s2.record(22000,"MI Smart TV"); 
  s1.display(); 
  s2.display(); 
} 
}

Output-

24575.0 Samsung LED
22000.0 MI Smart TV

Related Topics

Java Integer remainder Unsigned() method

The remainderUnsigned() method of Java Integer class returns the unsigned remainder by dividing the first and second argument. Syntax public static int remainderUnsigned(int dividend, int divisor)  Parameters The ‘dividend’ and ‘divisor’ represents the value...

1 minute read.

Comparetoignorecase in Java

In Java, the function compareToIgnoreCase ( ) is part of the String class, which is part of the java.lang package. It is used to compare any two strings while disregarding...

4 minutes read.

Method and Block Synchronization in Java

The Synchronization is performed in multi-threading concept. The multi-threading is a concept of parallel running of a program for the execution. In the multi-threading concept, the threads are run by...

3 minutes read.

Uses of Java

Java is used in many real-world Java applications, including technologies and tools. This Java programming language has become the backbone for developing many applications. In areas like embedded systems and...

3 minutes read.

Java Boyer Moore

A string searching or matching technique called the Boyer-Moore algorithm was created in 1977 by Robert S. Boyer and J. Strother Moore. It is the most popular and effective string-matching...

9 minutes read.

Copy data/content from one file to another in java

In this article, you will be acknowledged about how to copy data or content from one file to another file. Also, you will be acknowledged about the classes and methods...

3 minutes read.

Java Session

Session indicates interval of time. A session is a simple  time interval in which servers and client interacts. To maintain the state of the client or user we use technologies...

5 minutes read.

Java String concat() method:

Java String concat() method is used to add the given String to the end of the current String. Syntax: public String concat(String str) Parameter: Str: String to be concatenated at the end of current...

1 minute read.

String Declaration in Java

A string is a group of characters. In Java, the string can be treated as both class and datatype. In Java programming, the String class have many advantages. Everything in...

3 minutes read.

Thread Scheduler in java

Scheduling: it is defined as the execution of multiple threads on a single CPU in some order is called scheduling. Preemptive-priority scheduling: This algorithm schedules threads based on their priority relative to other...

11 minutes read.

Packages in Java

Packages in Java can be defined as an assortment for grouping various classes and interfaces based on their performance. It is a catalog for holding various java files. They provide...

4 minutes read.

Java Sort String

In this article, you will be acknowledged about how to sort a string in Java. Introduction Firstly, let us revise what is string Strings are collections of characters that are frequently used in...

4 minutes read.

Heap Implementation in Java

The root node or parent node of a Java heap is compared to its left and right offspring, and the children are then ordered in line with the comparison.Assuming that...

9 minutes read.

Deadlock in Java

Deadlock is when two or more processes wait for the state to do their tasks, but none of them can do so. It is a very common problem that one...

6 minutes read.

Sealed Class in Java

What is a Sealed Class in Java? In programming, the two main issues that must be taken into account when creating an application are security and control flow. The use of...

5 minutes read.

How to use Lambda Expression in Java?

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single method interface using an...

4 minutes read.

Minimum XOR value pair in Java

In this section, you will discuss about minimum XOR value pair in Java. The objective is to enforce a value that indicates the least XOR values of the two numbers from...

4 minutes read.

Coin change problem in dynamic programming

In this tutorial, we will understand a popular problem called the coin changeproblem through dynamic programming. This problem checks the logical and critical thinking ability of the person. Dynamic Programming...

5 minutes read.

Majority Element in Java

It's an extremely intriguing question that is commonly asked in job interviews at prestigious IT firms like The Google, Amazon, TCS, and The Accenture, etc. By figuring out the solution, one may...

10 minutes read.

Java Math nextAfter() Method

The nextAfter() method of Math class returns the floating-point value adjacent to the first argument in direction of the second argument. Syntax: public static double nextAfter (double start, double direction)public static float...

2 minutes read.