elibraryportal Logo

Object and Class in Java


1) Object

Object is real life entities that has state, behavior and identity is known as an object.
For example, a chair, pen, table, keyboard, bike, etc. every thing is an object

  1. State : It is represented by attributes of an object. It also reflects the properties of an object.
  2. Behavior : It is represented by methods of an object. It also reflects the response of an object with other objects.
  3. Identity : It gives a unique name to an object and enables one object to interact with other object

Example : Dog

Objec Example in Java

2) Class

Class is blue print of an object that means It represents the set of properties or methods.

class can contain that is:

  • Fields
  • Methods
  • Constructors
  • Blocks
  • Nested class and interface

Syntax of class declare :


What is Method in Java .?

Method is like a function which is used to pass data, as a parameters, into a method, expose the behavior of an object.

Advantage of Method

  • Code Reusability
  • Code Optimization

Example :

Output

Method in Java

new keyword in Java

→ Objects are created by the help of "new" keyword. new keyword is used to allocate memory at runtime

new keyword is used to create a new object of a class.

Example : Create a new instance of a class:

Full Example1 :

Output

New Keyword Example in Java

Example2 :

Output

New Keyword Example in Java

Initialize object

There are 3 ways to initialize object in Java.

  1. By reference variable
  2. By method
  3. By constructor

1) Initialization Reference variable

initialize the object through a reference variable.

Example1 :

Output : (1)save by the class Student.java name and run TestEx see in fig..

Reference variable Example in Java

Output : (2) Direct save by the class TestEx.java name and run TestEx see in fig..

Reference variable Example in Java

2) Initialization through method

We are creating the objects of Student class and initializing the value to these objects by invoking the insertRecord method. Here, we are displaying the data of the objects by invoking the display() method.

Example1 :

Output

Initialization through method Example in Java

3) Initialization through a constructor

Next Topic discuss, More Details....

Create an object in Java?

There are three ways to create an object in java. That is....

  • By new keyword
  • By newInstance() method
  • By clone() method
  • By deserialization
  • By factory method etc.

Anonymous object

 Anonymous means nameless. An object which has no reference is known as an anonymous object. It can be used at the time of object creation only.

 If you have to use an object only once, an anonymous object you can use :

 Calling method through a reference:

 Calling method through an anonymous object

Example

Output:

Anonymous Example in Java
Next TopicConstructor