Java常用类型
类型名称 | 字节占位 | 取值大小 |
---|---|---|
byte | 1 | -128 ~ 127 |
short | 2 | -2^15 ~ 2^15-1 |
int | 4 | -2^31 ~ 2^31-1 |
long | 8 | -2^63 ~ 2^63-1 |
float | 4 | 2^-149 ~ 2^128-1 |
double | 8 | 2^-1074 ~ 2^1024-1 |
char | 2 | 0 ~ 2^16-1 |
boolean | 1 | 0 ~ 1 |
string | 4 | 0 ~ 65534 |
封装
将类信息隐藏起来,并对外提供访问方法,可以有效提升安全性
public class Student implements Serializable {
//将类属性设置为仅自己访问
private Long id;
private String name;
private Integer sex;
// 对外提供访问方法
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
}
继承
- 在需要额外的对类进行扩展而不改变原有类数据的情况下使用
- 只能继承一个父类并使用父类公开属性与方法
- 可以重写父类方法的实现
public class Parent {
int numParent = 10;
int num = 100;
public void method(){
System.out.println("父类成员变量:"+numParent);
}
public void methodParent(){
System.out.println("父类成员方法!");
}
}
public class Childer extends Parent{
int numChilder = 20;
int num = 200;
public void method(){
System.out.println("子类成员变量:"+numChilder);
}
public void methodChilder(){
System.out.println("子类方法!");
}
public void methodParent(){
System.out.println("重写父类成员方法!");
}
}
public class ExtendDemo {
public static void main(String[] args) {
Parent parent = new Parent();
// 父类的实体对象只能调用父类的成员变量
System.out.println("父类:" + parent.numParent); // 结果:10
Childer childer = new Childer();
System.out.println("调用父类:" + childer.numParent); // 结果:10
System.out.println("子类:" + childer.numChilder); // 结果:20
/** 输出结果为200,证明在重名情况下,如果子类中存在则优先使用,
* 如果不存在则去父类查找,但如果父类也没有那么编译期就会报错。
*/
System.out.println(childer.num); // 结果:200
/**
* 通过成员方法调用成员变量
*/
childer.method(); // 结果:10
childer.methodParent(); //结果:重写父类成员方法!
}
}
多态
多态是同一个行为具有多个不同表现形式或形态的能力
比较常见的是
public class MultiDemo {
public static void main(String[] args) {
// 多态的引用,就是向上转型
Animals dog = new Dog();
dog.eat();
Animals cat = new Cat();
cat.eat();
// 如果要调用父类中没有的方法,则要向下转型
Dog dogDown = (Dog)dog;
dogDown.watchDoor();
}
}
class Animals {
public void eat(){
System.out.println("动物吃饭!");
}
}
class Dog extends Animals{
public void eat(){
System.out.println("狗在吃骨头!");
}
public void watchDoor(){
System.out.println("狗看门!");
}
}
class Cat extends Animals{
public void eat(){
System.out.println("猫在吃鱼!");
}
}