SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,kenrick Mock
Chapter:
Polymorphism And Abstract Classes
Exercise:
Programming Projects
Question:1 | ISBN:9780132830317 | Edition: 5

Question

In Programming Project 7.3 from Chapter 7, the Alien class was rewritten to use inheritance. The rewritten Alien class should be made abstract because there will never be a need to create an instance of it, only its derived classes. Change this to an abstract class and also make the getDamage method an abstract method. Test the class from your main method to ensure that it still operates as expected.


TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

//Alien.java
public abstract class Alien 
{
	protected int damageType,health;
	protected String name;
	
	Alien(int type, String name, int damg)
	{
		this.health=type;
		this.name=name;
		this.damageType=damg;
	}
	public abstract int getDamage();
}
//Snake.java
public class Snake extends Alien
{

	Snake(int type, String name)
	{
		super(type, name,200);
	
	}
	public int getDamage()
	{
		return this.damageType;
	}

}
//Ogre.java
public class Ogre extends Alien
{

	Ogre(int type, String name) 
	{
		super(type, name, 100);
		
	}
	public int getDamage()
	{
		return this.damageType;
	}

}
//MarshmallowMan.java
public class MarshmallowMan extends Alien
{

	MarshmallowMan(int type, String name)
	{
		super(type, name, 200);
	
	}
	public int getDamage()
	{
		return this.damageType;
	}

}

//AlienPack.java
public class AlienPack
{
	private Alien[] a;
	public AlienPack(int countAliens)
	{
		
		a=new Alien[countAliens];
	}

	public void addAlien(Alien newAlien, int index)
	{
		a[index]=newAlien;
	}
	public Alien[] getAliens()
	{
		return a;
	}
	public int calculateDamage()
	{
		int d=0;
		for(int i=0;i<a.length;i++)
			d+=a[i].getDamage();
		return d;
		
	}
}
//TestDemo
public class TestDemo 
{

	public static void main(String[] args)
	{
	
		AlienPack ap=new AlienPack(3);
		ap.addAlien(new Ogre(10,"Mark"),0);
		ap.addAlien(new Snake(10,"Peter"),1);
		ap.addAlien(new MarshmallowMan(10,"John"),2);
		System.out.println("Total damages="+ap.calculateDamage());
	}

}

 

Output of the program code:

Total damages=500

 

0 0

Discussions

Post the discussion to improve the above solution.