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.  

  6. Syntax of defining java class is,

  7. <modifier> class <class-name>{

  8.   // members and methods

  9. }

  10. */

  11.  

  12. public class JavaClassExample{

  13. /*

  14.   Syntax of defining memebers of the java class is,

  15.   <modifier> type <name>;

  16.   */

  17. private String name;

  18. /*

  19.   Syntax of defining methods of the java class is,

  20.   <modifier> <return-type> methodName(<optional-parameter-list>) <exception-list>{

  21.   ...

  22.   }

  23.   */

  24. public void setName(String n){

  25. //set passed parameter as name

  26. name = n;

  27. }

  28. public String getName(){

  29. //return the set name

  30. return name;

  31. }

  32. //main method will be called first when program is executed

  33. public static void main(String args[]){

  34. /*

  35.   Syntax of java object creation is,

  36.   <class-name> object-name = new <class-constructor>;

  37.   */

  38. JavaClassExample javaClassExample = new JavaClassExample();

  39. //set name member of this object

  40. javaClassExample.setName("Visitor");

  41. // print the name

  42. System.out.println("Hello " + javaClassExample.getName());

  43. }

  44. }

  45.  

  46. /*

  47. OUTPUT of the above given Java Class Example would be :

  48. Hello Visitor

  49. */

0 comments: