java_面向对象_基础_1.1

  • 面向对象基础,赋值调用成员变量和成员方法。
//手机类
class Phone{
	String brand;  //成员变量。	类的属性。
	int price;   //【高级版】 private int price; 
	String color;  //【高级版】就是私有成员变量的应用

	//成员方法。  类的方法。
	public void call(String name){
		System.out.println("this is calling "+name+"打电话");
	}
	public void sendMessage(){
		System.out.println("qun fa  message!");
	}
	/*【高级版:获取值】
	public int getPrice(){
		return price;
	}
	//【高级版:设置值1.0】
	public void setPrice(int price){
		//price=p  int p
		this.price=price  //传入的值被赋值给这个对象的成员变量。
	} */
	/* 设置价格前,对价格进行判断。【设置值2.0】
	// 使用封装对成员变量进行校验值。【对成员变量age的校验方法。判断对象给成员变量赋的值时是否合法,只有在符合要求的情况下才给成员变量赋值。】
	public void setPrice(int price) {
		if(price < 0 || price > 3000) {
			System.out.println("手机的定价有问题!");  // ||表示或者
		}else {
			this.price=price;
		}
	}
	}
	*/
	/* 姓名获取值
	public String getName() {
		return name;
	}
	//姓名设置值
	public void setName(String n) {
		name = n;
	} */
}
//手机类的测试类。
class PhoneDemo{
	public static void main(String[] args){
		//类名 对象名 = new 类名();
		Phone mi=new Phone();  //创建类的对象
		
		System.out.println("phone is "+mi.brand+";-->price is "+mi.price+";-->color is "+mi.price);
		//对象的成员变量没有赋值,所以输出为空。 String --> null; int --> 0;
		
		//【高级版输出】
		System.out.println("price is : "+mi.getPrice());
		
		mi.brand="xiaomi"; 	//给对象的成员变量赋值
		mi.price=2599;
		mi.color="blue";
		System.out.println("phone is "+mi.brand+";-->price is "+mi.price+";-->color is "+mi.price);
		//通过对象名.成员变量名调用对象的成员变量。

		mi.call("肥羊");  //通过对象名给成员方法传入参数
		mi.sendMessage();  //调用成员方法。
		mi.playGame();
	}
}
发布了80 篇原创文章 · 获赞 0 · 访问量 1765

猜你喜欢

转载自blog.csdn.net/weixin_41272269/article/details/103633591