javatutelearn.com

Easy Learning


Home

Search Javatutelearn.com :



Java Class

  • A class defines common attributes and methods.
  • Class is defined using the keyword 'class' in java.
  • Class consists of variables and methods
  • Class servers as a template for objects.
  • An object is an instance of the class.
  • An object consists of variables defined in the class. Variables are used to store the data.
  • An object can call methods to process the data stored in the object.

Example


class student {
    
        String name; 
        int rollno;  
		String address;

        public void setdata (String n, int r, String ad)
        {
			name = n;
			rollno = r;
			address = ad;
        }
        public void getdata ()
        {

            System.out.println ("Your name is " + name);
			System.out.println ("Your roll no is " + rollno);
			System.out.println (" Your address is " + address);
		}

}

class demostudent {

   public static void main (String args[])
		{
            student s1 = new student();
            s1.setdata("Amit",123456, "Delhi");
			s1.getdata();
		}

} 

Explanation of the program

  • In this program, class named 'student' is defined.
  • It consist of three variables 'name','rollno' and address.
  • Two methods are defined in the class. Methods are 'setdata()' and 'getdata()'.
  • Method setdata() receives the data from user and stores the data to object variable.
  • Method getdata() displays data stored in object.
  • One more class named 'demostudent' is defined. This class consists of 'main()' method.
  • In main() method, one object s1 is defined.
  • Object s1 invokes the method 'setdata()' and pass data to this method.
  • After that, object s1 invokes the method 'getdata()' to display the data.

Output of the program

Your name is Amit 
Your roll no is 07896
Your address is Delhi		


© Copyright 2016-2024 by javatutelearn.com. All Rights Reserved.