一,private,public,protected和默认的权限区别
权限大小:public>protected>default>private
二,clone()复制对象
重新new一个对象再复制另一个对象的属性太过于麻烦。简单点直接调用clone方法。
代码:
Student student=new Student();
Student stu=student;
student.setName("张三");
student.setAge(18);
System.out.println(student);
System.out.println(stu);
如果你向这样作以为是复制对象哪么你就错了,这只是将stu对象的引用指向了student的引用(复制引用)。复制一个对象应该保证他们的引用不同,这样在你改变一个对象时另一个对象才不会改变。
测试:
Clone()方法对比;
public static void main(String[] args) throws CloneNotSupportedException {
Student student=new Student();
Student stu=student;
//复制对象
Student stu1=student.clone();
student.setName("张三");
student.setAge(18);
System.out.println(student);
System.out.println(stu);
System.out.println(stu1);
}
测试:
Student类代码:
public class Student implements Cloneable{
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
String str="我叫:"+this.name+",年龄:"+this.age;
return str;
}
@Override
protected Student clone() throws CloneNotSupportedException {
return (Student)super.clone();
}
}
图片解析:
注意
clone是浅拷贝的,也就是说拷贝的对象的引用类型属性还是同一个内存地址。这个时候要实现深拷贝要把它的引用类型也重写clone()方法用 类 对象名=对象名.clone()的方法辅助。
就像这个例子:
Person p = new Person(23, "zhang"); 2.Person p1 = (Person) p.clone();
String result = getName() == p1.getName() ? "clone是浅拷贝的" : "clone是深拷贝的";
//打印结果为:clone是浅拷贝的
System.out.println(result);
正确作法演示:
三,两种或(||,|)和与(&&,&)的区别
&运算符有两种用法:(1)按位与;(2)逻辑与。
&&运算符是短路与运算。逻辑与跟短路与的差别是非常巨大的,虽然二者都要求运算符左右两端的布尔值都是
true 整个表达式的值才是 true。
&&之所以称为短路运算是因为,如果&&左边的表达式的值是 false,右边的表达式会被直接短路掉,不会进行
运算。很多时候我们可能都需要用&&而不是&,例如在验证用户登录时判定用户名不是 null 而且不是空字符串,应
当写为 username != null &&!username.equals(""),二者的顺序不能交换,更不能用&运算符,因为第一个条件如
果不成立,根本不能进行字符串的 equals 比较,否则会产生 NullPointerException 异常。注意:逻辑或运算符(|)
和短路或运算符(||)的差别也是如此。