代码改变世界

Java学习笔记——继承、接口、多态

2017-03-07 19:31  Self_made  阅读(289)  评论(0编辑  收藏  举报

浮点数的运算需要注意的问题:

    BigDecimal operand1 = new BigDecimal("1.0");
    BigDecimal operand2 = new BigDecimal("0.8");
    BigDecimal subtract = operand1.subtract(operand2);
    BigDecimal divide = operand1.divide(operand2);
    System.out.println(subtract);//结果为0.2
    System.out.println(1 - 0.8);//结果为0.19999999999999996  

一、对象封装

对象的比较

    BigDecimal d = new BigDecimal("0.1");
    BigDecimal e = new BigDecimal("0.1");
    BigDecimal f = e;
    System.out.println(d == e);//不是同一对象,所以为false
    System.out.println(d.equals(e));//equals比较对象的值是否相同
    System.out.println(e == f);//绑定为同一对象
    System.out.println(d != e);//结果为true,因为的确没有参考同一对象值

对象实例的复制

    Clothes[] c1 = {new Clothes("blue", 'S'), new Clothes("red", 'L')};
    Clothes[] c2 = new Clothes[c1.length];
    for (int i = 0; i < c2.length; i++) {
        c2[i] = c1[i];
    }
    c1[0].color = "yellow"; 
    System.out.println(c2[0].color);//浅层复制,只是复制参考,没有将对象复制过去,System.arraycopy和Arrays.copyOf()也不可以,只能自行复制,内部元素单独复制  

字符串的编译

    String t1 = "Ja" + "va";//都是常量,编译时直接看为"Java"
    String t2 = "Java";
    System.out.println(t1 == t2);//结果为true  

数组的复制

int[] arr1 = {1,2,3};
    int[] arr2 = arr1;//指向同一数组,要想复制需另建新数组
    arr2[1] = 20;
    System.out.println(arr1[1]);  

static方法或区块中不可以出现this关键字,也不可引用非静态的成员变量,非静态的方法和区块,可以使用static数据成员或方法成员

public static int sum(int a, int... num){//不定长自变量,必须放在最后面,只能用一个,对象也适用
    	int sum = 0;
    	for (int i : num) {
    	    sum += i;
    	}
    	return sum;
	}  

Java中只有传值调用

class Customer{
	String name;
	public Customer(String name) {
    	this.name = name;
	}
}
        
Customer c1 = new Customer("张三");
some(c1);
System.out.println(c1.name);//显示李四
    
Customer c2 = new Customer("赵六");
other(c2);
System.out.println(c2.name);//显示赵六
 

static void some(Customer c){
    c.name = "李四";
}
static void other(Customer c){
    c = new Customer("王五");//建立新对象指定给c参考,原本参考的对象会被清除
}  

二、继承与多态

关于继承的几点总结
1、一方面可以避免重复定义的行为,同时也不能为了避免重复就是用继承,否则会引起程序维护上的问题。
2、继承需要结合多态灵活使用才能发挥出灵活的作用。
3、继承同样也可以让子类重新定义父类的方法,或者在父类中定义抽象方法从而将父类定义成抽象类(只能被继承而不能被实例化)。
4、继承的同时也可以重新定义细节,使用super调用父类方法的内容。重新定义时对于父类方法的权限,只能扩大不能缩小。子类通过指定super中的参数来决定调用父类的某一个构造函数。
多态:即使用单一接口操作多种类型的对象。单一接口可以是多种类型的父类,他们都属于父类这种类型,所以可以避免为每个类型重复定义方法,从而可以提高代码的维护性。

三、接口与多态

关于接口的几点总结
1、接口用于定义行为,使用interface关键字定义,接口中的方法不能直接操作,表示为public abstract,类操作接口使用implements关键字,操作接口时可以操作接口中的方法或是直接标示为abstract。
2、继承会有是一种的关系,接口操作表示拥有行为,,判断是方式为右边是不是拥有左边的行为。
3、类可以操作两个以上的接口,拥有两个以上的行为,类可以同时继承某个类,并操作某些接口。接口可以继承自另一接口,可以继承两个以上接口,继承父接口的行为,再在子接口中额外定义行为。
4、接口可以枚举常数,只能定义为public static final,可以省略。