封装类
封装的流程
私有化成员变量,使用private关键字修饰。
提供共有的get成员方法和set成员方法,在方法体中来在构造方法中调用set成员方法进行合理的判断。
package 封装类;
/**
* @author hg
* @version 1.0
* @date 2022/5/8 22:08
*/
public class people {
String name;
int age;
public people() {
}
public people(String name, int age) {
this.age = age;
this.name = name;
}
public void show() {
System.out.println("I‘m " + name + ", " + age);
}
}
class TestPeople {
public static void main(String[] args) {
people p=new people();
p.show();
people pp=new people("Bob",-18);
pp.show();
}
}
//我们发现这样写人的age这么可能是0岁或-18岁,错的很离谱。所以要用上了封装类
package 封装类;
/**
* @author hg
* @version 1.0
* @date 2022/5/8 22:21
*/
public class person {
private String name;
private int age;
public person() {
}
public person(String name, int age) {
this.age = age;
this.name = name;
}
public void show() {
System.out.println("I‘m " + name + ", " + age);
}
public void setAge(int age) {
if(age>0&&age<200)
this.age = age;
else
System.out.println("yours name is error");//在这里判断·
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
}
class TestPerson {
public static void main(String[] args) {
person p=new person();
p.show();
person pp=new person("Bob",-18);
pp.show();
p.setAge(-18);
}
}
package com.company.包装类;
/**
* @author hg
* @version 1.0
* @date 2022/5/8 22:20
*/
public class Animal {
public static void main(String[] args) {
Object o = 1; //你没有发现什么问题吗,Object是对象,0是引用类型,1也是对象,
int i = 1; // 而int是基本类型,1是对象,明显不相等,为什么可以了、
/*
**类产生对象,而o=1,1是由某个类产生的。,所以int这个基本类型经过包装类的包装
Integer integer=new Integer(1);
Object o=integer.valueOf();
*/
System.out.println(o);//
Object w=2;
System.out.println(w);
IntNumber intNumber = new IntNumber(1);
Object q=1;
System.out.println(q);//q=1
q= intNumber;
System.out.println(q);//q??
//在java开发者公司已经写过了,我只需要用它就行。具体这么写去看源码,在idea中创个类写下Integer,Ctrl+鼠标右键点他
Integer integer=new Integer(3);
Object o1=integer;
System.out.println(o1);//o1=3.
}
}
class IntNumber {
private int n;
public IntNumber(int n) {
this.n=n;
}
public int IntNumber(int n) {
return (int)n;
}
}