标签:vat 输入 特定 generate void ted 需要 tag 列表
封装:隐藏了内部的实现细节和属性,提供公用的访问方法;就像下饭店,不能直接找厨师,得找服务员点菜。所有的下饭店的人,都需要都得先找找服务员,而不能直接找厨师。
为什么要用封装?
1,提高安全性 2,用户执行用固定的访问方式访问 3,可以通过流程控制语句,控制赋值的准确性。比如 避免age=1000这种情况
练习:封装Person类
package com.test.day01; class Person{ private int age; //规定年龄范围 public void setAge(int age){ if(18<age&&age<65){ this.age=age; }else{ System.out.println("输入年龄不在范围里"); } } public int getAge(int age){ return age; } } public class TestPerson { public static void main(String[] args) { // TODO Auto-generated method stub
Person person = new Person(); person.setAge(55); System.out.println(person.getAge(33)); } }
重载:通常在一个类中方法名相同参数列表的 个数、位置、类型 不同 便是重载
有点:减少代码 方便记忆
package com.test.day01; public class Override { public void f(){ System.out.println("f"); } public void f(byte n){ System.out.println("byte"); } public void f(int n){ System.out.println("int"); } public void f(char n){ System.out.println("char"); } public void f(String n){ System.out.println("String"); } public void f(long n){ System.out.println("long"); } public void f(double n){ System.out.println("double"); } public static void main(String[] args) { // 实现重载 Override ove = new Override(); ove.f((byte)9); ove.f(9.1); ove.f(9L); ove.f("王傲"); ove.f("王"); } }
构造方法分为:默认构造器 无参构造器 有参构造器
构造方法的作用就是 初始化对象 是在创建对象时调用
无参构造器:
package com.test.day01; public class TestEmployee { public static void main(String[] args) { // TODO Auto-generated method stub Employee employee = new Employee(); System.out.println(employee.show()); } } class Employee{ private int on; private String name; private int age; public Employee(){ on = 11; name = "妖君"; age = 25; } public int getOn() { return on; } public void setOn(int on) { this.on = on; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String show(){ return on +","+name+","+age; } }
有参
package com.test.day01; public class TestEmployee { public static void main(String[] args) { // TODO Auto-generated method stub Employee employee = new Employee(11,"姚明",43); System.out.println(employee.show()); } } class Employee{ private int on; private String name; private int age; // public Employee(){ // on = 11; // name = "妖君"; // age = 25; // } public Employee(int on,String name,int age){ this.on=on; this.age=age; this.name=name; } public int getOn() { return on; } public void setOn(int on) { this.on = on; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String show(){ return on +","+name+","+age; } }
标签:vat 输入 特定 generate void ted 需要 tag 列表
原文地址:https://www.cnblogs.com/yaojun3/p/11509240.html