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()) ;
}
}
}