构造器
为什么学习构造器
- 真正知道面向对象如何得到。
- 能够掌握面向对象赋值的其他写法。
构造器的作用
注意
总结
this关键字
this.name指代的全局声明的name。
代码演示
创建类
package this关键词;
public class car {
String name;
double price;
public car(){
}
public car(String name,double price){
System.out.println("有参数构造器被执行");
this.name = name;
this.price = price;
System.out.println(name + "价格是" + price);
}
public void gowith(String name){
System.out.println(this.name + "正在和" + name+"进行比赛");
}
}
创建主程序
package this关键词;
public class testcar {
public static void main(String[] args) {
car c = new car("电脑",7999);
System.out.println(c.name);
System.out.println(c.price);
c.gowith("手表");
}
}
结果分析
封装
封装的实现步骤
总结
标准JavaBean
程序案例
package this关键词;
public class User {
private String name;
private double height;
private double salary;
public User(){
System.out.println("无参数构造器被触发");
}
public User(String name, double height, double salary) {
this.name = name;
this.height = height;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
package this关键词;
public class Usertest {
public static void main(String[] args) {
User u = new User();
u.setName("小王");
u.setHeight(181.5);
u.setSalary(40);
System.out.println(u.getName());
System.out.println(u.getHeight());
System.out.println(u.getSalary());
User u2 = new User("小红",169,15);
System.out.println(u2.getName());
System.out.println(u2.getHeight());
System.out.println(u2.getSalary());
}
}
结果演示
参考
黑马程序员
|