REMEMBER JAVA

MINTE9
2REMEMBER




INHERITANCE

p86 ! Used inappropriately, inheritance leads to fragile software. Superclass overriding methods could lead to undesired results.
 RunCode
import java.util.HashSet;
import java.util.Arrays;
import java.util.Collection;

class App {

    public static void main(String[] args) {

        MyHashSet<String> s = new MyHashSet<>();  

        s.addAll(Arrays.asList(new String[] {"A", "B", "C"})); // Set method

        System.out.println(s.getCount()); // 6 - Error (should be 3)
    }
}

class MyHashSet<E> extends HashSet<E> {

    private int count = 0;

    public MyHashSet() {
        super();
    }

    public int getCount() {
        return count;
    }

    @Override public boolean add(E e) {
        count++;
        return super.add(e); // Look Here
    }

    @Override public boolean addAll(Collection<? extends E> c) {
        count += c.size();
        return super.addAll(c); // Look Here
    }
}
... 27 lines
˄˄˄

COMPOSITION

p88 ! Give your new class a private field that references an instance of the existing class. The existing class becames a component to the new class.
 RunCode
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

class App {

    public static void main(String[] args) {

        MyHashSet<String> s1 = new MyHashSet<>(new HashSet<>());  
        MyHashSet<String> s2 = new MyHashSet<>(new TreeSet<>());  // Look Here

        s1.addAll(List.of("A", "B", "C"));
        s2.addAll(List.of("D", "E", "F"));

        System.out.println(s1.getCount()); // 3
        System.out.println(s2.getCount()); // 3
    }
}

class MyHashSet<E> {

    private int count = 0;
    private final Set<E> set;

    public MyHashSet(Set<E> s) {
        this.set = s;
    }

    public int getCount() {
        return count;
    }

    public boolean add(E e) {
        count++;
        return this.set.add(e); // Look Here
    }

    public boolean addAll(Collection<? extends E> c) {
        count += c.size();
        return this.set.addAll(c); // Look Here
    }
}
... 33 lines
˄˄˄

Questions    
No. 59   Interfaces Default
CARD
58
63

        A B C D E F
🔔
1/2