![]() |
![]() |
Java Interface | |
Java Class vs Interface | |
Java Multiple Inheritance | |
Java Nested Interface |
Java Packages | |
Java Built in packages | |
Java Package Access Specifiers |
Java Programs | |
Java Keywords Dictionary | |
Java Interview Questions |
An object is an instance of class. It has its own states and behaviour which is called as properties of object.
Ex- consider a class human which having states color,name,place,contact no etc. and the behaviour is of human is walking(), running(), teaching() etc.
The class defines only logical structure but object contains the actual data is to be stored. We can create any number of objects of a class. But every object stores the different data.
class Human { public static void main(String args[]) { Human h1; h1 = new Human(); // or you can write in single statement as Human h2 = new Human(); } }
Once the object of class is created, the dot (.) operator is used to access the methods and fields of a class or from outside the class.
Example – accessing the data from same class using object
class City { String CityName; int villages; float area; void display() { System.out.println("City name : "+CityName); System.out.println("Total Villages: "+villages); System.out.println("Area: "+area); } public static void main(String args[]) { City mycity; mycity = new City(); // initializing class variables using object; mycity.CityName = " "; mycity.villages = ; mycity.area = ; mycity.display(); // calling method using object } }
Output
In above example we have initialized the instance fields using object and called one member function using object mycity
Example – same example using two classes
class City { String CityName; int villages; float area; void display() { System.out.println("City name : "+CityName); System.out.println("Total Villages: "+villages); System.out.println("Area: "+area); } } class mainMethod { public static void main(String args[]) { City mycity; mycity = new City(); // initializing class variables using object; mycity.CityName = " "; mycity.villages = ; mycity.area = ; mycity.display(); } }
Output
Note : while compiling the program make sure you are compiling using the class name having main() method. Ex- java mainMethod |
In above example we have two classes in which City class contains all the data members and the second class contains only main method for creating an object.
You can define any numbers of classes, but while calling their methods we must create their objects.
To create multiple objects of a class, follow above same procedure for declaration but give them a different name just like a normal variable.