我可以: 邀请好友来看>>
ZOL星空(中国) > 技术星空(中国) > Java技术星空(中国) > java程序使用匿名调用的问题
帖子很冷清,卤煮很失落!求安慰
返回列表
签到
手机签到经验翻倍!
快来扫一扫!

java程序使用匿名调用的问题

60浏览 / 1回复

24019562

24019562

0
精华
1
帖子

等  级:Lv.1
经  验:117
  • Z金豆: 0

    千万礼品等你来兑哦~快点击这里兑换吧~

  • 城  市:
  • 注  册:2011-12-05
  • 登  录:2015-03-27
发表于 2011-12-05 21:32:59
电梯直达 确定
楼主

class student{
 private String name;
 private int stuno;
 private float english;
 private float math;
 private float computer;
 private float average;
 private float max;
 private float sum;  //类属性
 public student(String n,int s,float e,float m,float c){  //构造方法,为属性赋值
  this.setName(n);
  this.setStuno(s);
  this.setEnglish(e);
  this.setMath(m);
  this.setComputer(c);
 
 }
 public void setName(String n){
  name = n;
 }
 public void setStuno(int s){
  stuno = s; 
 }
 public void setEnglish(float e){
  english = e;
 }
 public void setMath(float m){
  math = m;
 }
 public void setComputer(float c){
  computer = c;
 }
 public String getName(){
  return name;
 }
 public int getStuno(){
  return stuno;
 }
 public float getEnglish(){
  return english;
 }
 public float getMath(){
  return math;
 }
 public float getComputer(){
  return computer;
 }
 public void sum(){    //设置求和方法
  sum = english + math + computer;
  System.out.println("姓名:" + name + " 学号:" + stuno + 'n' + "总成绩=" + sum); 
 }
 
 public void max(){    //设置求最大值方法
  max = math;
  max = max>english?max:english;
  max = max>computer?max:computer;
  System.out.println("最大值"  + max);
 }
 public void average(){   //设置求平均值方法
  sum = sum/3;
  System.out.println("平均值:" + sum);
 }

}
public class studentDemo{
 public static void main(String args[]){  
  new student("张三", 24019563,80.7f, 90.4f, 84.5f).sum();      //使用匿名方法实例化对象,注意直接加方法进行调用
  new student("张三", 24019563,80.7f, 90.4f, 84.5f).max();      //使用匿名方法实例化对象,注意直接加方法进行调用
  new student("张三", 24019563,80.7f, 90.4f, 84.5f).average();     //使用匿名方法实例化对象,注意直接加方法进行调用
  student stu1 = new student("李四",24019562 , 80.5f , 90.2f, 84.4f);    //声明并实例化对象
  stu1.sum();
  stu1.average();
  stu1.max();
  

 }
}

姓名:张三      学号:24019563
总成绩=255.6
最大值90.4
平均值:0.0
姓名:李四      学号:24019562
总成绩=255.1
平均值:85.03333
最大值90.2

为什么输出值张三的平均值为0

aabingoo

aabingoo


精华

帖子

等  级:Lv.1
经  验:6
发表于 2011-12-14 13:13:37 1楼
new student("张三", 24019563,80.7f, 90.4f, 84.5f).sum();
new student("张三", 24019563,80.7f, 90.4f, 84.5f).max(); //使用匿名方法实例化对象,注意直接加方法进行调用
new student("张三", 24019563,80.7f, 90.4f, 84.5f).average(); //使用匿名方法实例化对象,注意直接加方法进行调用


这三条语句总共创建了三个对象(为什么?因为你都用new这个关键字了,new就是用来创建对象的),第三条语句在创建了新对象之后只是调用了average方法,此时并没用对sum进行赋值,所以sum的值还是默认的初值0.所以就为0了。。看懂了么?




高级模式
星空(中国)精选大家都在看24小时热帖7天热帖大家都在问最新回答

针对ZOL星空(中国)您有任何使用问题和建议 您可以 联系星空(中国)管理员查看帮助  或  给我提意见

快捷回复 APP下载 返回列表