Wednesday, 16 July 2014

Class in Java


A class is a group of objects that has common properties. It is a template or blueprint from which objects are created.
A class in java can contain:
  • data member
  • method
  • constructor
  • block
  • class and interface

Syntax to declare a class:

  1. class <class_name>{  
  2.     data member;  
  3.     method;  
  4. }  

Simple Example of Object and Class

In this example, we have created a Student class that have two data members id and name. We are creating the object of the Student class by new keyword and printing the objects value.
  1. class Student1{  
  2.  int id;//data member (also instance variable)  
  3.  String name;//data member(also instance variable)  
  4.   
  5.  public static void main(String args[]){  
  6.   Student1 s1=new Student1();//creating an object of Student  
  7.   System.out.println(s1.id);  
  8.   System.out.println(s1.name);  
  9.  }  
  10. }



No comments:

Post a Comment