A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© zyw2xsr 初级黑马   /  2015-7-25 01:13  /  242 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

最近刚学到构造函数然后自己练习写了个简单程序,程序代码和运行结果如下图。我的疑问:1.怎么才能使价格设定setprice和构造函数相结合,比如对象a打印出来的结果应该直接是没有该价格电脑?
                 2.public int getPrice()                        {
                                return price;
                        }这个函数有什么用?怎么用?
求各位帮忙解答下,谢谢。
class Computer
{
                private int price;//定义价格属性
                private String runspeed;//定义运行速度
                //代码块
        {
                System.out.println("taishiji");
        }
        //价格公共访问出口
                public void setPrice(int x)
                {
                        if(x>100 && x<10000)
                        {
                                price=x;
                        }
                        else
                        {
                                System.out.println("没有该价格电脑");
                        }
                }
                        public int getPrice()
                        {
                                return price;
                        }
                //构造函数
                Computer(int price)
                {
                        this.price=price;
                }
                Computer(int price,String runspeed)
                {
                        this.price=price;
                        this.runspeed=runspeed;
                }
                //   成员函数
                public void run()
                {
                        System.out.println("price="+price+"|"+"runspeed="+runspeed);
                }
                public boolean compare(Computer y)
                {
                        return this.price==y.price;
                }
}
class ComputerPeizhi
{
        //主函数
        public static void main(String[] args)
        {
                Computer a=new Computer(12000);
                a.setPrice(10000);
                a.run();
                Computer b=new Computer(2000,"很快");
                b.run();
                System.out.println(a.compare(b));
        }
}


运行结果.png (2.93 KB, 下载次数: 0)

运行结果.png

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马