位置:首页 > Java技术 > java实例在线教程 > Java方法重载实例

Java方法重载实例

Java中如何重载方法呢?

解决方法

本示例显示根据类型和参数个数的方法重载。

class MyClass {
   int height;
   MyClass() {
      System.out.println("bricks");
      height = 0;
   }
   MyClass(int i) {
      System.out.println("Building new House that is "
      + i + " feet tall");
      height = i;
   }
   void info() {
      System.out.println("House is " + height
      + " feet tall");
   }
   void info(String s) {
      System.out.println(s + ": House is "
      + height + " feet tall");
   }
}
public class MainClass {
   public static void main(String[] args) {
      MyClass t = new MyClass(0);
      t.info();
      t.info("overloaded method");
      //Overloaded constructor:
      new MyClass();
   }
}

结果

上面的代码示例将产生以下结果。

Building new House that is 0 feet tall.
House is 0 feet tall.
Overloaded method: House  is 0 feet tall.
bricks