Java教学 Lesson3

完整示例代码

// TestDrive表示这是一个driver class(驱动类)
public class ClassroomTestDrive
{
  public static void main(String[] args)
  {
    // 用Person创造黄种人、白种人和黑种人,需要对skinColor和hairColor做很多重复的赋值。
    Person reno = new Person("DingLei", 181, 84.2,"yellow", "black");
    Person pudding = new Person("ChenKexuan", 161, 45,"yellow", "black");
    Person shelly = new Person("HuangYujia", 168, 49,"yellow", "black");
    
    Person bryant = new Person("Kobe Bryant", 192, 100, "black", "black");
    Person smith = new Person("Will Smith", 183, 85, "black", "black");
    Person obama = new Person("Barack Hussein Obama", 185, 79, "black", "black");
    
    Person adam = new Person("Adam", 185, 80, "white", "golden");
    Person pitt = new Person("Brad Pitt", 180, 72, "white", "golden");
    Person beckham = new Person("David Beckham", 183, 75, "white", "golden");
    
    // 用YellowRace创造黄种人,比起Person可以少传入skinColor和hairColor两个参数。
    YellowRace renoY = new YellowRace("DingLei", 181, 84.2);
    YellowRace puddingY = new YellowRace("ChenKexuan", 161, 45);
    YellowRace shellyY = new YellowRace("HuangYujia", 168, 49);
    
    BlackRace bryantB = new BlackRace("Kobe Bryant", 192, 100);
    WhiteRace beckhamW = new WhiteRace("David Beckham", 183, 75);
    
    // 调用新添加的方法
    renoY.asianSquat(); 
    // reno.asianSquat(); 会导致编译错误,因为reno是Person类型的对象,不具备asianSquat方法。
    System.out.println();
    
    // 观察重写方法的区别
    reno.eat("apple", 200);
    renoY.eat("apple", 200);
    System.out.println();
    
    // 观察部分重写
    renoY.introduceMyDog();
    System.out.println();
    
    // 观察不同SubClass的重写
    renoY.eat("apple", 200);
    beckhamW.eat("apple", 200);
    bryantB.eat("apple", 200);
    System.out.println();
    
    
    // 掷骰子游戏,体会多态的机制
    int diceNumber =(int)(5 * Math.random() + 1);
    System.out.println("The dice numebr is " + diceNumber);
    
    Person theUnluckyGuy;
    
    if(diceNumber % 3 == 1)
    {
      theUnluckyGuy = renoY;
    }
    else if(diceNumber % 3 == 2)
    {
      theUnluckyGuy = beckhamW;
    }
    else
    {
      theUnluckyGuy = bryantB;
    }
    
    theUnluckyGuy.eat("apple", 200);
    System.out.println();
    
    
    // 对象的兼容性 - Downcast(向下转换)
    // 参数的兼容性 - 可以传入SubClass的对象
    Person renoP = new YellowRace("DingLei", 181, 84.2);
    ((YellowRace)renoP).makeFriendsWith(bryant);
    ((YellowRace)renoP).makeFriendsWith(bryantB);
    System.out.println();    
    
    // 抽象类不能实例化,但可以作为reference type
    Animal renoA = new YellowRace("DingLei", 181, 84.2);
    renoA.eat();
    System.out.println();    
    
    // 接口不能实例化,但可以作为reference type
    Flyable bird = new Bird();    
    System.out.println(bird.isFlying());
    System.out.println();    
    
    // 观察Comparable接口的compareTo方法
    System.out.println(reno.compareTo(pudding));
    System.out.println();    
    
    // 观察Object类的toString方法
    System.out.println(reno.toString());
    System.out.println();        
    
    // 观察Object类的equals方法
    Person reno2 = new Person("DingLei", 181, 84.2,"yellow", "black");    
    System.out.println(reno.equals(reno2));
    System.out.println();   
    
    // 观察Object类的hashCode方法 
    System.out.println(reno.hashCode());
    System.out.println(reno2.hashCode());
    System.out.println();   
  }
}

// 用extends关键字来表示继承
public class YellowRace extends Person
{
  // 能够继承public的变量和方法,自动包含以下方法
  // introduceMyself()
  // growUp()
  // eat()
  
  // 不能继承private的变量和方法,不能直接访问以下示例变量
  // name
  // height
  // weight
  
  // 新添加的instace variables
  String brainTalent;
  String physicalTalent;
  String mentleTalent;
  
  
  // SubClass需要定义自己的constructor
  public YellowRace(String psnName, double psnHeight, double psnWeight)
  {
    // 第一步,先调用Person的构造器,对继承下来的instance variables初始化
    super(psnName,psnHeight,psnWeight,"yellow","black");

    // 第二步,对新添加的instance variables初始化
    brainTalent = "High IQ";
    physicalTalent = "Stamina";
    mentleTalent = "Diligence";    
  }
  
  // 新添加的methods
  public void asianSquat()
  {
    // 不能直接访问name,要调用accessor
    System.out.println(getName() + " is Aisan-Squating.");
  }
  
  // method override - 重写Person中定义的eat方法
  public void eat(String foodName, double foodCalorie)
  {
    double increasedWeight = foodCalorie * 0.004;
    System.out.println(getName() + "'s weight increased " + increasedWeight + "kg after having a " + foodName + ".");
  }
  
  // partial override - 部分重写,先执行Person中的方法,再额外添加code
  public void introduceMyDog()
  {
    super.introduceMyDog();
    
    System.out.println("We don`t eat dogs!!");
  }
  
  public void makeFriendsWith(Person someGuy)
  {
    System.out.println(getName() + " and " + someGuy.getName() + " are friends now");
  }
  
}

// Person的SubClass
public class WhiteRace extends Person
{
  public WhiteRace(String psnName, double psnHeight, double psnWeight)
  {
    super(psnName,psnHeight,psnWeight,"white","golden");
  }
  
  public void eat(String foodName, double foodCalorie)
  {
    double increasedWeight = foodCalorie * 0.006;
    System.out.println(getName() + "'s weight increased " + increasedWeight + "kg after having a " + foodName + ".");
  }
}

// Person的SubClass
public class BlackRace extends Person
{
  public BlackRace(String psnName, double psnHeight, double psnWeight)
  {
    super(psnName,psnHeight,psnWeight,"black","black");
  }
}

// abstract class(抽象类)
abstract class Animal
{
  // 可以包含instance variables
  private double weight;

  // 可以包含methods
  public double getWeight()
  {
    return weight;
  }

  public void setWeight(double newWeight)
  {
    weight = newWeight;
  }

  // 至少会有一个abstract method(抽象方法)
  public abstract void walk();
  public abstract void eat();

}

// interface(接口)
interface Flyable
{
  // 不可以包含instance variables
  
  // 至少会有一个abstract method(抽象方法)
  void fly();
  boolean isFlying();
}

// 同时继承SuperClass和实现interface
public class Bird extends Animal implements Flyable
{
  // 实现Animal的抽象方法
  public void walk()
  {
    
  }  
  
  // 实现Animal的抽象方法
  public void eat()
  {
    
  }
  
  // 实现Flyable的抽象方法
  public void fly()
  {
    
  }
  
  // 实现Flyable的抽象方法
  public boolean isFlying()
  {
    return false;
  }
}


// class是一个模板或者蓝图
// 创建一个class的过程,把variables和methods组合在一起,就称为encpsulation(封装)
// Animal是Person的SuperClass, Comparable是Person需要实现的Interface
public class Person extends Animal implements Comparable
{
  // instance variables(实例变量), 代表对象的state
  // instance variables通常是private的,这都是为了information hiding(信息隐藏)
  // instance variables属于class scope(类范围),范围作用于整个类
  private String name;
  private double height;
  private double weight;
  private String skinColor;
  private String hairColor;
  
  private final int HEAD_COUNT = 1;
  private final int ARM_COUNT = 2;
  private final int LEG_COUNT = 2;
  
  
  // static variables(静态变量),作用于整个类而不是单个对象
  public static long worldPopulation = 7600000000L;
  public static final String BIOLOGICAL_CLASSIFICATION = "Primates";
  
  
  // methods(方法,通常省略instance的叫法),代表对象的behavior
  // methods通常是public的
  public void walk()
  {
  }  
  
  // static methods(静态方法),作用于整个类而不是单个对象
  public static void extinction()
  {
    worldPopulation = 0;
  }
  
  // default constructor(默认构造器),没有参数,只能提供一些合理的初始值
  public Person()
  {
    name = "Nobody";
    height = 0;
    weight = 0;
    skinColor = "yellow";
    hairColor = "black";
  }
  
  // custom constructor(自定义构造器),有参数,这是经常使用的构造器
  public Person(String psnName, double psnHeight, double psnWeight, String psnSkinColor, String psnHariColor)
  {
    name = psnName;
    height = psnHeight;
    weight = psnWeight;
    skinColor = psnSkinColor;
    hairColor = psnHariColor;
  }
  
  // 典型的accessor(访问器),用来返回对象的信息
  public String getName()
  {
    return name;
  }
  
  // 典型的mutator(更改器),用来设置对象的信息
  public void setName(String newName)
  {
    name = newName;
  }
  
  // 具有业务特征的accessor
  public void introduceMyself()
  {
    System.out.println("Hi, I`m " + name + ".");
    System.out.println("My height is " + height + "cm, and my weight is " + weight + "kg.");
    System.out.println("The color of my skin is " + skinColor + ", and the color of my hair is " + hairColor + "!");    
  }

  // 具有业务特征的mutator
  public void growUp()
  {
    height += 1;
    weight += 0.5;
  }
  
  // 连续三个eat方法代表 method overload(方法重载)
  public void eat()
  {
    double increasedWeight = weight * 0.05;
    System.out.println(name + "'s weight increased " + increasedWeight + "kg after eating something.");
  }

  public void eat(String foodName)
  {
    double increasedWeight = weight * 0.05;
    System.out.println(name + "'s weight increased " + increasedWeight + "kg after having a " + foodName + ".");
  }

  public void eat(String foodName, double foodCalorie)
  {
    double increasedWeight = foodCalorie * 0.005;
    System.out.println(name + "'s weight increased " + increasedWeight + "kg after having a " + foodName + ".");
  }
  
  // petName属于local scope(局部范围),作用范围仅限于方法内,两个petName互相不影响
  public void introduceMyDog()
  {
    String petName = "DaoDao";

    System.out.println("My pet is a dog, its name is " + petName + ".");
  }

  public void introduceMyCat()
  {
    String petName = "MaoMao";

    System.out.println("My pet is a cat, its name is " + petName + ".");
  }

  // local variable(局部变量)的优先级高于instance variables(实例变量)
  public void introduceMyself2()
  {  
    String name = "DaoDao";      
    System.out.println("My pet is a dog, its name is " + name + ".");

    System.out.println("Hi, I`m " + name + ".");
    System.out.println("My height is " + height + "cm, and my weight is " + weight + "kg.");
    System.out.println("The color of my skin is " + skinColor + ", and the color of my hair is " + hairColor + "!");      
  }
  
  // this关键字指代当前的object
  public void introduceMyself3()
  {  
    String name = "DaoDao";      
    System.out.println("My pet is a dog, its name is " + name + ".");

    System.out.println("Hi, I`m " + this.name + ".");
    System.out.println("My height is " + height + "cm, and my weight is " + weight + "kg.");
    System.out.println("The color of my skin is " + skinColor + ", and the color of my hair is " + hairColor + "!");      
  }
  
  // Comparable接口定义的抽象方法,必须实现它
  public int compareTo(Object obj)
  {
    // 第一步,将obj转化为Person
    Person anotherPerson = (Person)obj;
    
    // 第二步,thisPerson和anotherPerson进行比较
    if(this.height < anotherPerson.height)
    {
      return -1;      
    }
    else if(this.height > anotherPerson.height)
    {
      return 1;
    }
    else      
    {
      return 0;
    }
  }
  
  // Object类定义的toString方法,一般都要重写它
  public String toString()
  {
    return "name: " + name + ", height: " + height + ", weight: " + weight + ", skinColor: " + skinColor + ", hairColor: " + hairColor;
  }
  
  // Object类定义的equals方法,一般都要重写它  
  public boolean equals(Object obj)
  {
    Person anotherPerson = (Person)obj;
    
    boolean isEqual = (this.name == anotherPerson.name) 
                   && (this.height == anotherPerson.height) 
                   && (this.weight == anotherPerson.weight) 
                   && (this.skinColor == anotherPerson.skinColor) 
                   && (this.hairColor == anotherPerson.hairColor);
    
    return isEqual;      
  }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值