java中对象的使用

新建一个class类
在这里插入图片描述

//定义成员变量brand(品牌)与price(价格)
public class Phone {
    
    
    String brand;
    int price;
//  创建打电话的方法call与sendMessage
    public void call(){
    
    
        System.out.println("打电话");
    }
    public void sendMessage(){
    
    
        System.out.println("发短信");
    }
}

再建一个操作类
新建

使用对象

1.使用成员变量

  •   格式: 对象名.变量名
    
  •   范例: p.brand;
    
  • 2.使用成员方法

  •   格式:对象名.方法名();
    
  •   范例:p.call();
    
public class PhoneDemo {
    
    
    public static void main(String[] args) {
    
    
//        创建对象
        Phone p=new Phone();
//        使用成员变量
        System.out.println(p.brand);
        System.out.println(p.price);
/*        -------------
      输出:null  0   默认输出值String为null,int为0(堆内存)
*         -------------
*/
        //  使用成员变量
        p.brand="苹果";
        p.price=4999;
        System.out.println(p.brand);
        System.out.println(p.price);

//        使用成员方法
        p.call();
        p.sendMessage();
    }
}

运行结果
在这里插入图片描述

Guess you like

Origin blog.csdn.net/weixin_45090657/article/details/119719194