student student - 5 months ago 23
Java Question

linked list inheritance java

public class Link {
public static Link LAST = new Link(-1);
public Link next;
public int myId;
public Link() {
this(10);
}
public Link(Link next) {
this(20);
this.next = next;
}
protected Link(boolean b) {
this(99);
}
private Link(int myId) {
this.myId = myId;
}
@Override
public String toString() {
return "Link #" + myId;
}
}
public class DataLink<T> extends Link {
private T value;
public DataLink(T value) {
this(value, new Link(false));
}
public DataLink(T value, Link parent) {
super(parent);
this.value = value;
}
@Override
public String toString() {
return super.toString() + " (" + value.toString() +")";
}
}
public class Main {
public static void main(String[] args) {
************************
}
}


By replacing the line ************************ with

System.out.println(new DataLink<>(new Link()).next);

it prints Link # 99, How does it reach protected Link(Boolean b)?

CSK CSK
Answer

You can use any JAVA IDE to trace the steps

new DataLink<>(new Link()).next

is getting the NEXT LINK object of the DataLink's parent class (Link) because DataLink class doesn't have next object.

this is the steps

1.new DataLink<>(new Link())
2.this(value, new Link(false));  
    3.protected Link(boolean b) {    //from new Link(false)
          this(99); 
    4. this.myId = myId;  // myId = 99, from this(99)
5.super(parent); //calling public Link(Link next)
6.this.next = next; //next = link object with myId=99

so when you call new DataLink<>(new Link()).next, .next will call the next object in parent class which will print Link # 99