對象的特征
定義一個類的步驟
使用對象
- 創(chuàng)建對象
類名 對象名=new 類名();
- 引用對象成員跺涤;引用類的屬性;引用類的方法梯刚。
變量的作用域
- 成員變量:成員變量的作用域在整個類內(nèi)部都是可見的(java給初始值)
- 局部變量:局部變量的作用域僅限于定義它的方法(jav不給初始值)
-- 在同一個方法中冗恨,不允許有同名局部變量,在不同的方法中,可以有同名局部變量
-- 在同一個類中项栏,成員變量和局部變量同名時,局部變量具有更高的優(yōu)先級
例題
public class dog {
int weight;
String name;
public void eat()
{
weight++;
System.out.println("謝謝主人");
}
public void show() {
System.out.println("我現(xiàn)在的重量為"+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];//定義一個數(shù)組蹬竖,骰子一共有六個面
public void init() //初始化數(shù)組
{
for(int i=0;i<6;i++) //數(shù)組里存儲的值為1-6
{
value[i]=i+1;
}
}
//扔骰子
public int throwcount()
{
//扔骰子產(chǎn)生隨機數(shù)
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();//創(chuàng)建一個新對象
int count[]=new int[7];//定義一個數(shù)組
Dice.init(); //初始化
for(int i=1;i<10000;i++) //計數(shù)沼沈,記錄出現(xiàn)的次數(shù)
{
int num= Dice.throwcount();
count[num]++;
}
for(int i=1;i<count.length;i++) //輸出數(shù)組
{
System.out.println(i+"出現(xiàn)"+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();
}
}
}