×

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

Features of Java

The objective of the Java programming language is to provide portability, security, and simplicity. In spite of this, Java has a number of features that makes it a popular language...

5 minutes read.

Java Private keyword

A Java access modifier is a private keyword. It can be used to inner classes, methods, and variables. It is the type of access modifier that is most constrained. Privately declared...

4 minutes read.

Java Queue Interface

Queue interface is a subtype of Collection interface. All methods in the Collection interface are also available in the Queue interface. It provides operations of Collection and also some additional...

2 minutes read.

How to set timer in Java

In this article, you will be very well equipped with the knowledge to set timer in java. The timer in java can be set by using timer class provided by...

3 minutes read.

Shopping Bill in Java

Java Shopping Bill Here in this program, we are about to create a JAVA class called Products which will have some properties or attributes like prod_name (Product Name ), qty (quantity),...

4 minutes read.

Swing Program in Java

Java Swing is part of Java Foundation Classes (JFC). The swing toolkit is used to generate Graphical User Interface (GUI) for programs written in Java. The Java swing API is...

4 minutes read.

Process and Thread in Java

Process It is a program that is running on your computer. The process is a heavy-weight, which takes memory separately to other processes. The process may be a small background task like spell-checker; it...

11 minutes read.

Difference Between BufferedReader and FileReader

BufferedReader: To read data from a specified character stream, two classes are used: buffered readers and file readers. Both of them have advantages and disadvantages. Although how they operate is the...

6 minutes read.

JDBC vs ODBC

Difference Between JDBC and ODBC ODBC: ODBC (Open Database Connectivity) is the accepted method for accessing databases among organisations and programmers. A database is linked to other programmes, such as word processors, spreadsheets,...

4 minutes read.

Java Math getExponent() Method

The getExponent() method of Math class returns the unbiased exponent of the argument. Syntax: public static int getExponent (double d) Parameters: The parameter ‘d’ represents the double value. Return Value: The getExponent () method returns the...

1 minute read.

Annotations in Java

Annotations in Java Java Annotations are metadata about the source code. They do not have any direct effect on the execution of the java program. Annotations in Java were introduced in...

4 minutes read.

Difference between Aggregation and Composition in Java

What is Aggregation? Before we start discussing Aggregation, we have to know some general information about our classes in java. Generally we have two members in our classes , the first...

8 minutes read.

Creation of Multi Thread in java

What are threads in Java? We can use threads to facilitate parallel processing. Threads are helpful when you wish to execute several pieces of code concurrently. A thread is a small process...

3 minutes read.

Java String equalsIgnoreCase() method

equalsIgnoreCase() method compares two Strings based on the their content but ignore the case. Syntax public boolean equalsIgnoreCase(Objects anObject) Parameter anObject: Object to be compared with the current String without case consideration. Returns It returns true...

1 minute read.

Java String endsWith() method

Checks whether this String ends with the specified suffix or not. Syntax public boolean endsWith(String Suffix) Parameter Suffix : It takes suffix as a parameter  i.e. Sequence of characters Returns It returns true when the current...

1 minute read.

Interfaces and Classes in Strings in Java

CharBuffer: CharBuffer is utilized to implement the CharSequence interface. With the help of the mentioned class, we can allow character buffers to be utilized instead of CharSequences. We can consider the illustration...

4 minutes read.

Java Program to Print Permutations of String

A string is given and you need to print all the possible ways for that string. Permutation is arranging the characters of a string to get outputs from the given...

3 minutes read.

Magnanimous Number in java

Magnanimous Number When the left and right halves of a majestic number are combined, the result is invariably a prime number, which must have at least two digits. The number's left...

3 minutes read.

Davis Staircase Problem in Java

Davis has several stairs in his home and prefers to ascend one, two, or three steps at a time. As a highly clever youngster, he thinks about how many ways...

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