Java面向对象----封装概念
封装
信息隐藏,隐藏对象的细节
访问修饰符
public
private
protected
默认
属性封装的实现
方法封装的目的(隐藏方法实现细节)
package com.tanlei.newer; public class TeacherDemo { public static void main(String[] args) { teacher t=new teacher(); //t.name("zhangs"); t.setName("zhangs"); t.setAge(23); System.out.println(t.getAge()); } } class teacher{ private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { if( age<25) { System.out.println("年龄太小了"); this.age=age; }else { this.age=age; } } }
UML类图(建模语言,图形化语言)
类的构造方法
对属性进行初始化赋值
new 操作符 {自动调用}
package com.tanlei.newer; public class ContstructorDemo { public static void main(String[] args) { person person=new person("长沙",3); //在堆中开辟空间,给属性分配默认的初始值 //假设属性一开始就赋值了,就进行赋值工作 //调用构造方法来进行赋值 System.out.println(person.toString()); } } class person{ private String name; private int age; public person(String name,int a) { this.name=name; this.age=a; } 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; } @Override public String toString() { return "person [name=" + name + ", age=" + age + "]"; } }
static关键字
类变量(静态变量)
类方法(静态方法)
优先于对象的存在
可以通过类名.成员调用
package com.tanlei.newer; public class Static { public static void main(String[] args) { Account.num1++; System.out.println(Account.num1); } } class Account{ public static int num1=1;//静态变量 public int num2=2; public void shownum1() { System.out.println(num1); } public void shownum2() { System.out.println(num2); } }
//static语句块 类被加载的时候就会执行,只会执行一次,优先于构造方法的执行
static {
}