In: Computer Science
Write a line of code that indicates to the compiler that the method being declared overrides a superclass method.
Write a line of code that specifies that class Fly inherits from class Insect.
Call superclass Insect's toString method from subclass Fly's tostring method.
Call superclass Insect's constructor from subclass Fly's constructor, assume that the constructor receives an integer for number of legs and a string for the ability it has.
For each problem given, the solution is provided below:
The line that shows the superclass method overrides in the derived class. The line is in bold form.
public class A{
public double compute_cost()
{
return 50.0;
}
}
public class B extends A{
//The function of Base class
//A overrides in the derived class B.
public double compute_cost()
{
return 55.0;
}
}
Explanation:
The line of code that specifies that class Fly inherits from class Insect is as follows:
The line is in bold form.
public class Insect{
//Body of class Insect.
}
public class Fly extends Insect{
//Body of class Fly.
}
Explanation:
The calling of superclass Insect's toString method from subclass Fly's tostring method is as follows:
public class Insect{
public String toString()
{
return("Base class Insect toString() method.");
}
}
public class Fly extends Insect{
@Override
//The toString() function of class Insect
//is called in the dervied class.
public String toString()
{
return (super.toString());
}
}
Explanation:
The calling of superclass Insect's constructor from subclass Fly's constructor. The code is provided below:
public class Insect{
//Declare the variables.
public int legs_count ;
public string ability;
//Parameterized constructor of the class Insect.
public Insect(int legs, string ability)
{
//Assign the values.
legs_count = legs;
ability = ability;
}
}
public class Fly extends Insect{
//Constructor of derived class Fly.
public Fly(int legs, string insect_ability)
{
//Calling of the parameterized constructor of
//the base class Insect.
super(legs, insect_ability);
}
}
Explanation: