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

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

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

1、对象封装

对象的比较ide

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()也不能够,只能自行复制,内部元素单独复制

字符串的编译this

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

数组的复制code

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参考,本来参考的对象会被清除
}

2、继承与多态

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

3、接口与多态

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

相关文章
相关标签/搜索