使用对象类型作为方法的参数:
package 面向对象;
public class PhontTest {//使用对象类型作为方法的参数
public static void main(String[] args) {
Phone one = new Phone();
one.brand = "华为";
one.color = "蓝";
one.price = 1399;
System.out.println(one.brand);
System.out.println(one.color);
System.out.println(one.price);
one.call("小青");
one.sendMessage();
}
}
使用对象类型作为方法的返回值:
package 面向对象;
public class Phone02Test {//使用对象类型作为方法的返回值
public static void main(String[] args) {
Phone two = getPhone();
System.out.println(two.brand);
System.out.println(two.price);
System.out.println(two.color);
}
public static Phone getPhone(){
Phone one = new Phone();
one.brand = "苹果";
one.price = 9000.0;
one.color = "玫瑰金";
return one;
}
}
封装性:
把普通的对象进行封装,对象的属性设为私有的,对外提供get和set方法,其他类只能通过get和set对对象属性值进行操作。
Setter/Getter:
必须叫setXxx或者是getXxx命名规则。
对于Getter来说,不能有参数,返回值类型和成员变量对应;
对于setter来说,不能有返回值,参数类型和成员变量对应。
Person类:
package 面向对象.封装性;
public class Person {
String name;
private int age;//年龄有限制,用private关键字
public void show(){
System.out.println("姓名:" + name +"年龄:"+ age);
}
//这个成员方法,专门用于向age设置数据
public void setAge(int age){
if (age < 100 && age > 0 )
this.age = age;
else System.out.println("输入错误!");
}
//这个成员方法,专门私语获取age的数据
public int getAge(){
return age;
}
}
测试类:
package 面向对象.封装性;
public class PersonText {
public static void main(String[] args) {
Person person = new Person();
person.show();
person.name = "李四";
// person.age = -20;
person.setAge(-20);
person.show();
}
}
结果:
姓名:null年龄:0
输入错误!
姓名:李四年龄:0
特殊情况:
对于基本类型当中的boolean值,Getter方法一定要写成isxxx的形式,而setXxx规则不变。
private boolean male;
public void setMale(boolean male){
this.male = male;
}
public boolean isMale(){
return male;
}
测试:
person.setMale(true);
System.out.println("是不是男生:" + person.isMale());