Java Class Example /* Java Class example. This Java class example describes how class is defined and ...

Java Class Example

02:30 PASSOVE INCOME 0 Comments

                   Java Class Example

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

0 comments: