Java Reference
In-Depth Information
public double computeStrength() {
return goodPower respect Math . random ( ) ;
} public String toString() {
return super .getName()+ " is a superhero that has good power = " +
goodPower+ " and respect = " +respect ;
public class Villain extends FictionalCharacter
private int evilPower ;
private int narcissism;
public Villain(String name, int evilPower , int narcissism)
super (name) ;
this . evilPower = evilPower ;
this . narcissism = narcissism;
public double computeStrength() {
return evilPower narcissism Math . random ( ) 0.9;
} public String toString() {
return super .getName()+ " is a villain that has evil power = " +
evilPower+ " and narcissism = " +narcissism;
Note that we have multiplied the power of villains by 0.9 just because we do not like
them (i.e., we do not want to give them a fair shot at winning a fight with a superhero).
As expected, both subclasses have an implementation of the computeStrength method. If
this method was missing from one of the subclasses, then a compilation error would be
We have added a toString method to both classes. We will use this method to print a
fictional character. Note that since the variable name inside the FictionalCharacter class
is private, we had to resort to calling a method to get the name of the fictional characters.
Even subclasses do not have access to the private variables of the superclass.
We are now ready to start building our main class: we will call it FaceOff . For starters,
let us create several fictional characters and just print them. We will allow the player to
specify the parameters of the characters. A menu method that prints a menu and lets the
user choose between entering a villain or entering a superhero will be created. We will store
the fictional characters inside an ArrayList because we do not know how many fictional
characters the user will want to create. The first iteration of the class follows.
import java . util . ;
public class FaceOff {
public static void main(String [] args) {
ArrayList < FictionalCharacter > characters = new ArrayList <> () ;
populateCharacters(characters) ;
for (FictionalCharacter character : characters) {
System.out. println(character . toString()) ;
} public static void populateCharacters(ArrayList < FictionalCharacter >
characters) {
Search WWH ::

Custom Search