Java文件执行流程
- 编译:将.java文件编译为虚拟机可以识别的.class字节码文件
- 解释:虚拟机执行java字节码文件,将其转化为机器可以执行的机器码
- 执行:机器执行机器码
面向对象的三大特性
- 封装
- 继承
- 多态
深拷贝和浅拷贝
- 浅拷贝代码举例
public class Person implements Cloneable {
private Address address;
public Person(Address address){
this.address = address;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Address implements Cloneable{
private String name;
public Address(String name){
this.name = name;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public static void main(String[] args) throws CloneNotSupportedException {
Person person1 = new Person(new Address("北京"));
Person person2 = (Person)person1.clone();
System.out.println(person1 == person2); //false
System.out.println(person1.getAddress() == person2.getAddress()); //true
}
浅拷贝之后对象重新拷贝了一份,但是在对象里面的引用并没有重新拷贝
- 深拷贝代码举例
public class Address implements Cloneable{
private String name;
public Address(String name){
this.name = name;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Person implements Cloneable {
private Address address;
public Person(Address address){
this.address = address;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
protected Object clone() throws CloneNotSupportedException {
try {
Person person = (Person) super.clone();
person.setAddress((Address) person.getAddress().clone());
return person;
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
}
public static void main(String[] args) throws CloneNotSupportedException {
Person person1 = new Person(new Address("北京"));
Person person2 = (Person)person1.clone();
System.out.println(person1 == person2); //false
System.out.println(person1.getAddress() == person2.getAddress()); //false
}
深拷贝不仅仅拷贝了对象,还拷贝了对象里面的引用,此外深拷贝还可以使用序列化方式进行拷贝
- 另外还有一种引用拷贝,就是直接引用使用的对象,即直接指向该对象堆中的地址,不进行拷贝
hashCode()和equals()
每个对象都有一个hashCode,相同对象的hashCode肯定是一样的,所以可以使用hashCode来判断对象是否相等来提高判断效率,但是也有小概率不同的对象的hashCode也是相同的,所以要使用equals来保证判断对象完整与否的准确性,在使用过程中,首先使用hashCode,如果hashCode不相等,那么他们绝对不是相同的,如果他们相等,则会再使用equals来判断这两个对象是否相等