For the questions below, consider the following class definition: public class A
ID: 3779085 • Letter: F
Question
For the questions below, consider the following class definition: public class AClass { protected int x; protected int y; public AClass(int a, int b) { x = a; y = b; } public int addEm( ) { return x + y; } public void changeEm( ) { x++; y--; } public String toString( ) { return "" + x + " " + y; } } Consider that you want to extend AClass to BClass. BClass will have a third int instance data, z. Which of the following would best define BClass'constructor? 1. public BClass(int a, int b, int c) { super( ); } 2. public BClass(int a, int b, int c) { z = c; } 3. public BClass(int a, int b, int c) { super(a, b, c); } 4. public BClass(int a, int b, int c) { super(a, b); z = c; } 5. public BClass(int a, int b, int c) { x = a; y = b; z = c; }
Explanation / Answer
Answer:
Option 4. public BClass(int a, int b, int c) { super(a, b); z = c; } would be best define BClass constructor because keyword Super always refers the immediate parent class.It is used to call the parent class constructor.
Program:
import java.io.*;
class AClass
{
protected int x;
protected int y;
public AClass(int a, int b)
{
x = a;
y = b;
}
public int addEm( )
{
return x + y;
}
public void changeEm( )
{
x++;
y--;
}
public String toString( )
{
return "" + x + " " + y;
}
}
public class BClass extends AClass
{
protected int z;
public BClass(int a, int b, int c) { super(a, b); z = c; }
}
Output:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.