In: Computer Science
What output is produced by the following code? Explain how it works (at least 5 lines).
class Super {
int num = 1;
int id = 2;
}
class Sub extends Super {
int num = 3;
public void display() {
System.out.println(num);
System.out.println(super.num);
System.out.println(id);
}
}
public class Inheritance1 {
public static void main (String[] args) {
Sub obj = new Sub();
obj.display();
}
}
===============================
Example of "Explain how it works"
Sample Question:
What output is produced by the following code? Explain
how it works.
class student {
String name;
int age;
}
public class q6_ArryList1 {
public static void main(String args[]) {
ArrayList<student>myArray = new ArrayList<>();
for(int i=0; i< 4; i++){
student s = new student();
s.name="Emily"+i;
myArray.add(s);
}
for (int i = 0; i<myArray.size(); i++){
System.out.format("%s %n", myArray.get(i).name, myArray.get(i).age);
}
System.out.println();
for (int i = 0; i<myArray.size(); i++){
if (i % 2 ==0) {
myArray.remove(1); }
}
for (int i = 0; i<myArray.size(); i++){
System.out.format("%s %n", myArray.get(i).name, myArray.get(i).age);
}
}
}
Answer:
Emily 0
Emily 1
Emily 2
Emily 3
Emily 0
Emily 3
How it works:
In this problem, an arrayList is created, then Emily + i is added
to the arrayList where i is the for loop variable. The for loop
goes from 0 inclusive to 4 exclusive. Therefore the arrayList
contains [Emily0,Emily1, Emily2, Emily3]. After this, another for
loop that goes through the arrayList is executed. An if statement
inside the for loop gives a condition that if i %2 = 0, then remove
the value at position 1. Thus, at 0, index 1 which is Emily1 is
removed. At 1, nothing is removed. At 2, Emily2 is removed. Lastly,
the arrayList, which contains[Emily0 and Emily3] is printed.
Question :
Answer :
3
1
2
How it works: