java学习--类与对象

java学习–类与对象

类的定义与对象的使用

类的定义与对象的使用

  类的定义步骤:

public 类名;
//定义成员变量
数据类型 变量名;
//定义成员方法
public void 方法名(){}

对象的使用:

1.对象的创建:
类名 对象名=new l类名;
2.使用成员变量:
对象名.变量名;
3.使用成员方法:
对象名.方法名();

package day01;
//手机类
public class Phone {
    //成员变量
    String brand;
    int price;
    //成员方法
    public void call(){
        System.out.println("打电话");
    }
    public void sendMessage(){
        System.out.println("发短信");
    }
}
package day01;
//测试类
public class PhoneDemo {
    public static void main(String[] args) {
        Phone p=new Phone();
        System.out.println(p.brand);
        System.out.println(p.price);
        p.brand="红米";
        p.price=2000;
        System.out.println(p.brand);
        System.out.println(p.price);
        p.call();
        p.sendMessage();
    }

}

类的私有成员的使用

类的私有成员的使用
private 数据类型 变量名;
用setXxx()和get()Xxx()的方法分别用于设置成员变量的值和获取成员变量的值

package test01;
    /*
    学生类
     */
    public class Student {
        private String name;
        private  int age;
        public void setName(String n){
            name=n;
        }
        public String getName(){

            return name;
        }
        public  void setAge(int m) {
            age = m;
}
public int getAge() {
        return age;
    }
    public void show() {
            System.out.println(name+","+age);

    }
}
package test01;
/*
学生测试类
 */
public class StudentDemo {
    public static void main(String[] args) {
     Student s=new Student();
     s.setName("林琳");
     s.setAge(18);
     s.show();
    }
}


案例2

package test02;
public class Phone {
    private String brand;
    private int price;
    public void setBrand(String brand) {
        this.brand = brand;
    }
  public String getBrnd() {
        return brand;
    }

    public void setPrice(int price) {
        this.price = price;
        }

    public int getPrice() {
    return price;
    }
    public static class PhoneDemo {
        public static void main(String[] args){
            Phone s=new Phone();
            s.brand="小米";
            s.price=1999;
           System.out.println(s.getBrnd()+","+s.getPrice()) ;
        }
    }
}



 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值