例子:
Cat.java:
package com.wys.javaoop; /** * 宠物猫类 * @author snape */ public class Cat { //成员属性: String name; //昵称 默认值为null int month; //年龄 默认值为0 double weight; //体重 默认值为0.0 String species; //品种 默认值为null //成员方法: public Cat() { System.out.println("我是无参构造方法"); } public Cat(String name){ System.out.println("我是带参构造方法"); } //跑动方法 public void run(){ System.out.println("猫跑动"); } //跑动方法,重载 public void run(String name){ System.out.println(name + "跑动"); } //吃东西方法 public void eat(){ System.out.println("猫吃东西"); } }
CatTest.java:
package com.wys.javaoop; public class CatTest { public static void main(String[] args) { Cat one = new Cat(); one.run(); Cat two = new Cat("mimi"); two.run(); } }
结果: