热爱开源,热爱linux
分类: LINUX
2008-10-24 21:29:33
| |
|
class classname { type instance-varable1; type instance-varable2; //... type instance-varableN; type metbodname1(parameter-list) { //body of method } type metbodname2(parameter-list) { //body of method } //... type metbodnameN(parameter-list) { //body of method } } |
class Sameple { int a,b; int sum() { return a+b; } } |
class Sample { int a,b; // constructor Sample(int x,int y) { a = x; b = y; } int sum() { return a+b; } } |
class Example { public static void main(String args[]) { Sample ob = new Sample(-99,88); System.out.println(ob.sum()); } } |
// Demonstrate method overload class OverloadDemo { void test() { System.out.println("No parameters"); } void test(int a) { System.out.println("a:" + a); } void test(int a,int b) { System.out.println("a and b:" + a + " " + b); } void test(double a) { System.out.println("double a: " + a); } } 下面类说明了重载的test()方法。 class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); double result; // call all versions of test() ob.test(); ob.test(10); ob.test(10,20); result = ob.test(123.4); } } |
//A simple exmaple of recursion class Factorial { //this is a recursive method int fact(int n) { int result; if (n == 1) return 1; result = fact(n-1) * n; return result; } } class Recursion { public static void main(String arg[]) { Factorial f = new Factorial(); System.out.println("Factorial of 4 is " + f.fact(4); System.out.println("Factorial of 5 is " + f.fact(5); } } |
//Display all commad line arguments class CommandLine { public static void main(String arg[]) [ for (int i = 0;i < args.length; i++) System.out.println("args[" + i + "]: " + args[i]); } } |