Website For Developers

Class in Java

Example to understand the definition of the class in Java

public class Baby{

  String name;
  int age;
  void cry(){
    System.out.println( "Baby is crying." );
  void hungry(){
    System.out.println( "Baby is Hungry." );


Object in Java

Syntax of Creating an Object

Classname objectname = new classname();

Complete Example of class in Java

public class Baby { //class name

   String name = "Alen"; // member variable
   int age = 2; // member variable
   void cry(){ // member method
     System.out.println( "Baby is Crying." );
   void hungry(){ // member method
     System.out.println( "Baby is Hungry." );

   public static void main(String[] args) {
     Baby obj = new Baby(); //creating an object
     System.out.println( "Baby name is: " );
     System.out.println( "Baby age is: "+obj.age );


Baby name is: Alen
Baby age is: 2
Baby is Crying.
Baby is Hungry.

How to create separate file of class in java NetBeans?