第九天
关键字This
this代表当前对象,this就是所在函数所属对象的引用,哪个对象调用了this,this就代表哪个对象.this就是当前类的对象的地址值引用
构造方法
构造方法名和类名一致,没有具体的返回值类型,连void都没有,因为构造方法就是给类定义新的成员对象时用来给数据进行初始化的时候用的.
class Student{
private String name ;//姓名
private int age ; //年龄
//定义一个构造方法?
//无参构造方法
public Student(){
System.out.println("这是Student类的无参构造方法...") ;
}
//定义有参构造方法(带一个String类型的参数)
public Student(String name){//局部变量 "高圆圆"
//this.name = name ;
System.out.println("这是Student类带String类型的有参构造方法...") ;
}
//带一个int类型的有参构造
public Student(int age){
System.out.println("这是Student类带int类型的有参构造方法...") ;
}
//带两个参数的有参构造
public Student(String name,int age){
System.out.println("这是Student类带两个参数的有参构造方法...") ;
}
}
注意!
当书写类中的构造方法的时候,要是这个类没有提供构造方法,呢么系统会默认定义一个无参的构造方法,如果我们提供了有参构造方法呢么系统不会提供无参的构造方法了.建议直接定义一个无参的构造方法,目的是为方便类成员进行数据的初始化.
标准类
一个标准类其内部应有一下几点:
- 所有成员变量都由private所修饰
- 每一个成员变量都有一对get和set方法去调用修改他们的值.
- 一个无参的构造方法
- 一个有参的构造方法
//定义个手机,String有牌子,String颜色,int价格
class phone{
private String brand;
private String color;
private int price;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public phone(){}
public phone(String x,String y,int z){
this.brand = x;
this.color = y;
this.price = z;
}
public void call(){
System.out.println("打电话");
}
public void text(){
System.out.println("发短信");
}
}
测试类
public class phoneTest{
public static void main(String[] args){
phone p1 = new phone();
p1.setBrand("apple");
p1.setColor("Red");
p1.setPrice(4999);
System.out.println("brand :"+p1.getBrand()+"\n"+"color :"+p1.getColor()+"\n"+"price :"+p1.getPrice());
System.out.println("-------------------------------------------------------------------------------");
phone p2 = new phone("xiaomi","black",3299);
System.out.println("brand :"+p2.getBrand()+"\n"+"color :"+p2.getColor()+"\n"+"price :"+p2.getPrice());
}
}
结果
brand :apple
color :Red
price :4999
-------------------------------------------------------------------------------
brand :xiaomi
color :black
price :3299