《Head First Java》——对象的行为

类所描述的是 对象知道什么与执行什么!

 

调用两个参数的方法,并传入两个参数

void go(){

  TestStuff t = new TestStuff();

  t.takeTwo(12,34);

}

void takeTwo(int x,int y){

  int z =  x + y;

  System.out.println("Total is " + z);

}

你也可以将变量当作参数传入,只要类型相符就可以

void go(){

  int foo = 7;

  int bar = 3;

  t.takeTwo(foo,bar);

}

 

void takeTwo(){

  int z = x + y;

  System.out.println("Total is " + z);

}

 

Getter 和 Setter

Getter与Setter可让你执行get与set.Getter 的目的只有一个,就是返回实例变量的值。Setter的目的就是要取用一个参数来设定实例变量的值。

class ElectricGuitar {

  String brand ;

  int numOfPickkups;

  boolean rockStarUsesIt;

 

  String getBrand(){

  return brand;

}  

 

void setBrand(String aBrand){

  brand = aBrand;

}

 

int getNumOfPickups(){

  return numOfPickups;

}

void setNumOfPickups(int num){

  numOfPickups = num;

}

boolean getRockStarUsesIt(){

  return rockStarUsesIt;

}

void setRockStarUsesIt(boolean yesOrNo){

  rockStarUsesIt = yesOrNo;

}

}

封装

封装GoodDog

class GoodDog{

  private int size ;                                               //将实例变量设置成private

  

  public int getSize(){               //将getter 与setter 设定为public   //虽然次方法没有加上实质的功能性,但最重要的是允许你能够在事后改变心意,你可以回头把程序改得更加安全,更好。

  return size;

  }

  public void setSize(int s){

  size = s;

     }

}

void bark (){

  if (size > 60){

    System.out.println("Wooof!wooof!");

  } else if (size > 14){

    System.out.println("Ruff! ruff!");

  } else {

    System.out.println("Yip! yip!");

  }

}

 

class GoodDogTestDrive{

  public static void main(String [] args){

    GoodDog one = new GoodDog();

    one.getSize(70);

    GoodDog two = new GoodDog();

    two.getSize(8);

           System.out.println("Dog one:" + one.getSize());

    System.out.println("Dog two:" + two.getSize());

    one.bark();

            two.bark();

  }  

}

另外,任何有值可以运用到的地方,都可以调用方法的方式取得该类型的值:

int x = 3 + 24;

可以写成: int x = 3 + one.getSize();

 

数组中对象的行为

声明一个含有7个Dog引用的Dog数组

Dog [] pets ;                             //创建一个名字叫做 pets 的Dog类数组

pets = new Dog[7];                   //说明这个名字叫 pets 数组里面有几个对象;

 

然后,创建两个Dog对象并赋值为数组的前两项元素

pets[0] = new Dog();

pets[1] = new Dog();

 

调用这两个Dog对象的方法

pets[0].setSize(30);

int x = pets[0].getSize();

 

变量的比较

使用 == 来比较两个 primitive主数据类型,或者判断两个引用是否用同一个对象。

使用equals()来判断两个对象是否在意义上相等

 

Foo a = new Foo();

Foo b = new Foo();

Foo c = a;

 

if (a == b){// false}

if (b == c){//false}

if (a == c){//true}

 

转载于:https://www.cnblogs.com/Backstreet/p/5942489.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值