美文网首页
初始类和对象

初始类和对象

作者: 荐航 | 来源:发表于2018-02-24 19:08 被阅读0次

对象的特征

  • 属性
  • 方法

定义一个类的步骤

  • 定义类名
  • 编写类的属性
  • 编写类的方法

使用对象

  • 创建对象
    类名 对象名=new 类名();
  • 引用对象成员;引用类的属性;引用类的方法。

变量的作用域

  • 成员变量:成员变量的作用域在整个类内部都是可见的(java给初始值)
  • 局部变量:局部变量的作用域仅限于定义它的方法(jav不给初始值)
    -- 在同一个方法中,不允许有同名局部变量,在不同的方法中,可以有同名局部变量
    -- 在同一个类中,成员变量和局部变量同名时,局部变量具有更高的优先级

例题

  • 定义类dog
 public class dog {
        int weight;
        String name;
        public void eat()
        {
           weight++;
            System.out.println("谢谢主人");
        }
        public void show() {
            System.out.println("我现在的重量为"+weight);
        }
        public String getName() {
            String name="haha";
            System.out.println(name);
            return name;
        }
    }
 public class test1
{
    public static void main(String[] args) {
        dog nuonuo=new dog();
        nuonuo.getName();
        for(int i=1;i<=20;i++)
        {
            nuonuo.eat();
            nuonuo.show();
        }
    }
}
  • 掷骰子
public  class dice
{
    int[] value=new int[6];//定义一个数组,骰子一共有六个面
    public void init()    //初始化数组
    {
        for(int i=0;i<6;i++)  //数组里存储的值为1-6
        {
            value[i]=i+1;
        }
    }
    
    //扔骰子
    public int throwcount()
    {
        //扔骰子产生随机数
        int a=(int)(Math.random()*6); //下标随机0-5
        return value[a];              //value[0-5]
    }
}
public class throwdice
        {
            public static void main(String[] args) {
                dice Dice=new dice();//创建一个新对象
                int count[]=new int[7];//定义一个数组
                Dice.init();           //初始化
                for(int i=1;i<10000;i++)   //计数,记录出现的次数
                {
                    int num= Dice.throwcount();
                    count[num]++;
                }
                for(int i=1;i<count.length;i++) //输出数组
                {
                    System.out.println(i+"出现"+count[i]+"次");
                }

    }
}
public class vist {
    int age;
    String name;
    public void show()
    {
        if(age>=10 && age<=60)
        {
            System.out.println(name+age+"票价为20元");
        }
        else {
            System.out.println(name+age+"免费");
        }
    }
}
public class visttest {
    public static void main(String[] args) {
        vist person=new vist();
        while(true)
        {
            Scanner sc=new Scanner(System.in);
            System.out.println("请输入姓名");
            person.name=sc.next();
            if(person.name.equals("n"))
            {
                System.out.println("退出程序");
                break;
            }
            System.out.println("请输入年龄");
            person.age=sc.nextInt();

         person.show();
        }
    }
}

相关文章

网友评论

      本文标题:初始类和对象

      本文链接:https://www.haomeiwen.com/subject/jagfgxtx.html