Java – Class and Object

  • Objects are anything that exists in the world. A Class is a blueprint to develop objects.
  • If you consider creating objects like chair, table, cupboard, then you need to create class called Furniture.
  • A class contains variables and methods.
  • Variables are attributes or peoperties.
  • Method perform the functions or actions.

 

A Class looks like

 

Example program to understand objects :

output:

C:\> javac UsePerson.java
C:\> java UsePerson
Im Dara
Im 20 years old

We have two classes in a same source file. Then, which name should we use as a file name ?

You have to use the name of the class containing main() method. so we save the above source file as UsePerson.java.

The main() method:

A Java application can have any number of classes but any one class should contain a main() method. During runtime, the JVM will search for the main() method and start executing the statements in main() method.

The syntax is

public static void main(String [] args)
{
// statements
}

The new() operator

Using Person class, you can create any number of objects of type Person using new() operator.The syntax is

classname objectname = new classname();

To create an object for Person class, we use

Person personOne= new Person();

new Person() will create a object of type Person.
personOne is a variable name referring to the Person object.

The dot operator;

The variables and methods of Person class is available to all the objects of Person class. Those variables and method are accessed by using dot operator.

The name variable of personOne object is specified by personOne.name

personOne.name = “Dara”;

similarly, the age variable of personOne object is specified by personOne.age

personOne.age= 20;

 





Facebook Twitter Linkedin