×

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

Finding Odd Occurrence of a Number in Java

In this tutorial, we will learn how to find the odd occurrence of a number through a java program. Let us consider an array of non-negative integers. Here, except for one...

6 minutes read.

How to Convert Decimal to Octal in Java

How to Convert Decimal to Octal in Java There are two methods to convert Decimal to Octal: Using toOcatlString() method Using user-defined logic Using Integer.toOctalString() method The toOctalString() is astaticmethod of the Integer...

2 minutes read.

Java.sql.Time Format

In JDBC API as a cover aroundjava.util.Date that handles SQL-specific requirements we use the java.sql.Time. The java.sql.Time extends java.util.Date class. To represent SQL TIME, without a date this class is...

6 minutes read.

How annotations work in Java

Annotations were introduced by sun microsystem and are available from the java 1.5 version. In general, configurations can be done either by XML or by annotations. Hibernate and spring framework users prefer...

4 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.

Race Condition in Java

Java is a multi-threaded programming language, race conditions are more likely to arise. Mostly because data can change when multiple threads visit the same resource simultaneously. Race conditions are concurrency...

3 minutes read.

C# vs Java

Difference Between C# and Java C# and Java both languagesare popularly used programming languages. They both are derived from C/C++ programming and follow Object Oriented Programming approach. Even so, both these...

4 minutes read.

Multiple Inheritance Programs in Java

A component of the object-oriented notion known as multiple inheritances allows a class to inherit properties from multiple parent classes. When methods that have the same signature are present in...

4 minutes read.

Conditional operator in Java

In Java, there are around eight operators, and among them, three operators are used to evaluate the condition and decide the Result based on the Result of the evaluated condition. Below...

4 minutes read.

Anonymous Function in Java

A function defined as being unbound from an identifier is called an anonymous function. Because they permit access to variables within the scope of the contained function, these are a...

4 minutes read.

Java Strictfp Keyword

Strictfp is used to impose limits on floating-point calculation. It ensures that we will get the same result on every platform while performing an operation with the floating-point variable. The floating-point calculation is platform-dependent due...

1 minute read.

Even Odd Program in Java

Even Odd Program in Java The number that are completely divisible by 2 are even and the number that leaves remainder are odd numbers. For example, the numbers 2, 0, 4,...

5 minutes read.

Packages Program in java

Let us know what package is in the Java programming language, and later we will learn about types of packages and how to define a package. How to import Java...

4 minutes read.

How to Import Packages in Java

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Equidigital in Java

In this section, we will understand what is an equidigital number and how to write Java programs to locate them. It is commonly asked in academic settings and Java coding...

4 minutes read.

Convert IP to Binary in Java

Fundamental conversion, such as going from binary to decimal or vice versa, is a crucial activity in computers. Understanding IP addressing and subnetting is crucial for networking. The primary networking...

4 minutes read.

Java Integer compare() method

The compare() method of Integer class compares the two specified int values. Syntax public static int compare(int x, int y) Parameters The parameters ‘x’ and ‘y’ represent the first and second int values to...

2 minutes read.

Design of JDBC

Java applications may interface using database systems from many vendors using the Java Database Connectivity (JDBC) Application Software Interface (API) from Sun Microsystem. To connect spreadsheets, JDBC and database drivers...

3 minutes read.

Special Operators in Java

An operator in Java is a special symbol. It is used to perform operations on two or more variables.  We all know basic operations in Java. There are 8 types...

5 minutes read.

Java Extends vs Implements

Java: We known that the java is a pure object oriented programming language. Java programming language consists of many features such as portable, plat form independence, secured, robust, simple, architecture neutral,...

4 minutes read.