Join
Blogs
Questions
Videos
Tags
Members
Search
 
 
Create your own blog, earn points and get popular!

Java Class Example

  1. /*
  2. Java Class example.
  3. This Java class example describes how class is defined and being used in Java language.
  4. */
  5.  
  6. /*
  7. Syntax of defining java class is,
  8.  
  9.     <modifier> class <class-name>{
  10.    
  11.     // members and methods
  12.    
  13.     }
  14. */
  15.  
  16. public class JavaClassExample{
  17.    
  18.     /*
  19.     Syntax of defining members of the java class is,
  20.         <modifier> type <name>;
  21.     */
  22.    
  23.     private String name;
  24.    
  25.     /*
  26.     Syntax of defining methods of the java class is,
  27.    
  28.         <modifier> <return-type> methodName(<optional-parameter-list>) <exception-list>{
  29.             ...
  30.         }
  31.     */
  32.    
  33.     public void setName(String n){
  34.         //set passed parameter as name
  35.         name = n;
  36.     }
  37.    
  38.     public String getName(){
  39.         //return the set name
  40.         return name;
  41.     }
  42.    
  43.     //main method will be called first when program is executed
  44.     public static void main(String args[]){
  45.    
  46.         /*
  47.         Syntax of java object creation is,
  48.             <class-name> object-name = new <class-constructor>;
  49.         */
  50.        
  51.         JavaClassExample javaClassExample = new JavaClassExample();
  52.        
  53.         //set name member of this object
  54.         javaClassExample.setName("Visitor");
  55.        
  56.         // print the name
  57.         System.out.println("Hello " + javaClassExample.getName());      
  58.    
  59.     }
  60.  
  61. }
  62.  
  63. /*
  64. OUTPUT of the above given Java Class Example would be:
  65. Hello Visitor
  66. */
Your rating: None Average: 4 (5 votes)
Share this
Anonymous's picture

good example for begineers

good example for begineers
Anonymous's picture

Indeed , Class is essential

Indeed , Class is essential in Java and beginners always puzzles with questions like What is class in Java , how to use it etc.
Anonymous's picture

mind blowing

mind blowing

Post new comment