Examples of smaller Java programs that do various interesting things.

DemoClass.java 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /******************************************************************/
  2. /* Author: CS307 Course Staff */
  3. /* Date: February 14, 2005 */
  4. /* Description: Demos constructors, static vs instance methods, */
  5. /* and method overloading. */
  6. /******************************************************************/
  7. public class DemoClass
  8. {
  9. private int x;
  10. public DemoClass()
  11. {
  12. // assign default value
  13. x = 0;
  14. }
  15. public DemoClass(int x)
  16. {
  17. // use this.x to refer to the instance variable x
  18. // use x to refer to a local variable x (more specifically,
  19. // method parameter x)
  20. this.x = x;
  21. }
  22. public DemoClass(DemoClass otherDemo)
  23. {
  24. // copy the value from the otherDemo
  25. this.x = otherDemo.x;
  26. }
  27. // static method (aka class method)
  28. public static void s1() {
  29. return;
  30. }
  31. // instance method
  32. public void i1() {
  33. return;
  34. }
  35. // static calling static OK
  36. // static calling instance is a compile-time error
  37. public static void s2() {
  38. // i1(); // compile-time error
  39. s1(); // DemoClass.s1
  40. return;
  41. }
  42. // instance calling static OK
  43. // instance calling instance OK
  44. public void i2() {
  45. s1(); // DemoClass.s1();
  46. i1(); // this.i1();
  47. return;
  48. }
  49. // call various versions of overload() based on their
  50. // list of parameters (aka function signatures)
  51. public void overloadTester() {
  52. System.out.println("overloadTester:\n");
  53. overload((byte)1);
  54. overload((short)1);
  55. overload(1);
  56. overload(1L);
  57. overload(1.0f);
  58. overload(1.0);
  59. overload('1');
  60. overload(true);
  61. }
  62. public void overload(byte b) {
  63. System.out.println("byte");
  64. }
  65. public void overload(short s) {
  66. System.out.println("short");
  67. }
  68. public void overload(int i) {
  69. System.out.println("int");
  70. }
  71. public void overload(long l) {
  72. System.out.println("long");
  73. }
  74. public void overload(float f) {
  75. System.out.println("float");
  76. }
  77. public void overload(double d) {
  78. System.out.println("double");
  79. }
  80. public void overload(char c) {
  81. System.out.println("char");
  82. }
  83. public void overload(boolean b) {
  84. System.out.println("boolean");
  85. }
  86. public static void main(String[] args) {
  87. DemoClass dc = new DemoClass();
  88. dc.overloadTester();
  89. }
  90. }
  91. // end of DemoClass.java