This section is about the classes and objects in java.
Objects & Classes
ObjectsObject is the instance of the class which have 'behavior' and 'states' or we can say 'properties' in other words. For example, lion has states like color, breed etc and also have behaviors like-growling, roaring etc.
ClassA class is a template/blue print for defining the behavior and states of the objects.
Java Objects
If you look around, you will find many live example of objects like humans, bikes, cars, dogs etc.
Humans can have many states like name, complexion, nationality etc and the behaviors like talking, walking etc.
Java objects have very similar characteristics like real word objects having a state and behavior. A java object's behavior is shown via methods and it's state is stored in fields.
Object to object communication is done through methods and methods operates on object's internal state.
Java Classes
The classes in java act like blue print for making objects :
Given below a sample class :
public class MainClass {
private int aField;
public void aMethod() {}
}
Creating an Object
As mention above an object is created from a class. The object is created in java using 'new' keyword.
You can create an object as follows :
Mainclass mc=new Mainclass( );
You can access instance variable and method as follows :
mc.firstnumber;
mc.add();
Example :
Given below complete example with output snap :
Mainclass.java
package corejava; public class Mainclass { int myage; public Mainclass(String name) { // This constructor has one parameter, name. System.out.println("Name :" + name); } void setAge(int age) { myage = age; } int getAge() { System.out.println("Age :" + myage); return myage; } public static void main(String[] args) { /* Object creation */ Mainclass mc = new Mainclass("Ankit"); /* Call class method to set age */ mc.setAge(24); /* Call another class method to get age */ mc.getAge(); /* You can access instance variable as follows as well */ System.out.println("Fetched Value via object :" + mc.myage); } }
Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac
Mainclass.java C:\Program Files\Java\jdk1.6.0_18\bin>java Mainclass Name :Ankit Age :24 Fetched Value via object :24 |
[ 0 ] Comments