目录
- 封装
- 基本概念
- 总结
- 如何更好的封装
- 总结
- JavaBean
- 补充知识:成员变量,局部变量区别
- 综合案例
封装
面向对象的三大特征:封装,继承,多态。
封装:告诉我们,如何正确设计对象的属性和方法。
封装的原则:对象代表什么,就得封装对应的数据,并提供数据对应的行为。
基本概念
画圆需要的是圆的属性,是圆的行为。
门被关,李四被噶
总结
1.什么是封装啊?
告诉我们,如何正确设计对象的属性和方法。
原则:对象代表什么,就得封装对应的数据,并提供数据对应的行为。
2.理解封装思想有什么好处?
让编程变得很简单,有什么事,找对象,调方法就行。
降低我们的学习成本,可以少学、少记,或者说压根不用学,
不用记对象的那么多方法,有需要时去找就行
如何更好的封装
package com.itheima.encapsulation;
public class Student {
private int age;
public void setAge(int age){
if(age>=0&&age<=200){
this.age=age;
}else{
System.out.println("您的年龄数据有问题!");
}
}
public int getAge(){
return age;
}
}
package com.itheima.encapsulation;
public class Test {
public static void main(String[] args) {
Student s =new Student();
s.setAge(-23);
System.out.println(s.getAge());
}
}
总结
1.如何进行更好的封装?
- 一般会把成员变量使用private隐藏起来,对外就不能直接访问了。
- 提供public修饰的getter和setter方法暴露其取值和赋值。
JavaBean
package com.itheima.javabean;
public class User {
private String name;
private double height;
private double salary;
public User() {
}
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 com.itheima.javabean;
public class Test {
public static void main(String[] args) {
User u1 = new User();
u1.setName("吴彦祖");
u1.setHeight(180.5);
u1.setSalary(1000.0);
System.out.println(u1.getName());
System.out.println(u1.getHeight());
System.out.println(u1.getSalary());
User u2 = new User("古天乐",175,300000);
System.out.println(u2.getName());
System.out.println(u2.getHeight());
System.out.println(u2.getSalary());
}
}
补充知识:成员变量,局部变量区别
综合案例
package com.itheima.moviedemo;
public class Movie {
private String name;
private double score;
private String actor;
public Movie() {
}
public Movie(String name, double score, String actor) {
this.name = name;
this.score = score;
this.actor = actor;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
public String getActor() {
return actor;
}
public void setActor(String actor) {
this.actor = actor;
}
}
package com.itheima.moviedemo;
public class Test {
public static void main(String[] args) {
Movie [] movies = new Movie[3];
movies[0]= new Movie("长津湖",9.7,"吴京");
movies[1]= new Movie("我和我的父辈",9.6,"吴京");
movies[2]= new Movie("扑水少年",9.5,"王川");
for(int i =0;i<movies.length;i++){
Movie m = movies[i];
System.out.println(m);
System.out.println("电影名:"+m.getName());
System.out.println("得分:"+m.getScore());
System.out.println("主演:"+m.getActor());
System.out.println("-----------------");
}
}
}