There is no available constructor in the superclass (Java) - java

I have one super class, which called game that. It looks like this:
import java.util.ArrayList;
public class Game {
private ArrayList<Enemy> enemies = new ArrayList<Enemy>();
private ArrayList<Tower> towers = new ArrayList<Tower>();
private int corridorLength;
private int currentPosition = 0;
public Game(int corridorLength){
this.corridorLength = corridorLength;
}
public void addTower(int damage,int timeStep){
this.towers.add(new Tower(damage,timeStep)); // Add tower with
current position corrdor length
}
public void addEnemy(int health, int speed){
this.enemies.add(new Enemy(health,speed));
}
public void advance(){
this.currentPosition = this.currentPosition + 1;
if(this.currentPosition == this.corridorLength){
System.out.println("Game Over");
}
}
public void printDamage(){
System.out.println(this.towers.get(this.currentPosition));
}
}
The main focus is on the public void addTower(int, int)
So, I have a subclass called Tower:
public class Tower extends Game {
public Tower(int damage, int timeStep){
super.addTower(damage,timeStep);
}
public void getDamage(){
super.printDamage();
}
}
And subclass of the Tower subclass called Catapult:
public class Catapult extends Tower {
public Catapult(){
super(5,3);
}
}
I am new to Java and can't see what am I doing wrong here. Why do I need a default constructor for the Tower in the Game?

You need to explicitly declare default constructor in Game class.
public Game (){}
Since, Object instantiation chained to Object class during that, it will call its super class constructor. You have explicitly declared arg-constructor in Game, so default constructor won't be added automatically.

Related

Set methods in a subclass

I need to set values from the subclass by invoking the set method from the super class. I need to set monster name and health from the subclass
Alien class
public class Alien {
//Instance variables
public String monsterName;
public int HP;
//A method that sets monster properties
public void setValues(String monsterN, int health) {
monsterName = monsterN;
HP = health;
}
//A method that returns the monster name
public String getName() {
return monsterName;
}
//A method that returns monster's health
public int getHP() {
return HP;
}
//ToString method that prints out the info
public String toString() {
return("Monster name: " + getName() + "Monster's current health point: " + getHP());
}
}
Snake class
public class SnakeAlien extends Alien {
//Instance variable
//Set the snake values
Alien aObject = new Alien();
aObject.setvalues("Snake\n" 55));
}
The main class
public class Main {
public static void main(String[] args) {
Alien object = new Alien();
object.toString();
System.out.println(object);
}
}
I know how would I set these values through the main class, but I need to do it from the sub class SnakeAlien which inherets from the Alien class.
Because everything is public (which is terrible BTW) you can simply call the superclass' methods frimbthe subclasses. Not even super is needed.
Though, you should change members you don't want to reach from the outside to at least protected, and if you never want to make a pure Alien object, you should make that an avstract class.

private static list which contains all object constructed

I'm writing animation program, in which many balls are running around and bouncing.
I made Ball class which represents ball's behaviour.
When I implement ball's collisioin with another ball,
I have to check the all other balls.
So I made this class.
public class Ball{
private static final List<Ball> allBalls;
static{
allBalls = new ArrayList<>();
}
private Ball(){}
public static Ball getNewBall(){
Ball ball = new Ball();
allBalls.add(ball);
return ball;
}
public void collision(){
for(Ball b : allBalls){
//check whether b is colliding with me
//and if colliding, change speed of me and b.
}
}
}
Is this kind of design (to hold all objects in private static list) good or bad ?
What you should have is a BallManager class that will handle that stuff.
public class BallManager {
private static BallManager instance = new BallManager();
private BallManager(){}
public static BallManager getInstance() {
return instance;
}
public List<Ball> ballsInPlay = new ArrayList<>();
public void createBall(int x, int y) {}
public void checkCollisions() {
// loop ball list and check collisions
// perform cleanup based on collisions
}
private void ballCleanup(){}
}
public class Ball{
public Ball(){}
public void collision(Ball other){}
}
NOTE: Changed from static class to singleton. Also, fixed the compilation error by adding () after checkCollisions method
Create Singleton BallManager using enum.
enum singleton are best to use.
Improving the previous answer.
public enum BallManager {
INSTANCE;
public List<Ball> ballsInPlay = new ArrayList<>();
public void createBall(int x, int y) {}
public void checkCollisions() {
// loop ball list and check collisions
// perform cleanup based on collisions
}
private void ballCleanup(){}
}
public class Ball{
public Ball(){}
public void collision(Ball other){}
}

Java Classes and interface implementation

I am a beginner java programmer learning step by step how to code with Java.
I have this code that is an implementation of an interface in java.
Please assist me in debugging it.
Here is the interface:
package ke.munyiri.me;
public interface Hp {
public void scrollUp (int increment);
public void scrollDown (int decrement);
public void rightClick();
public void leftClick ();
}
and here is its implementation:
/**
*
*/
package ke.munyiri.me;
/**
* #author MUNYIRI
*
*/
public abstract class Mouse implements Hp {
char manufacturer;
char type;
static int scroll;
boolean click;
public static void main(String[] args){
public void scrollUp(int increment){
scroll = scroll + increment;
System.out.println("The mouse is scrolling up");
}
public void scrollDown (int decrement){
int scrollDown = scroll - decrement;
System.out.println("The mouse is scrolling down");
}
public void rightClick(){
boolean rightClick = true;
System.out.println("The mouse is right Clicking");
}
public leftClick(){
boolean leftClick = true;
System.out.println("The mouse is left Clicking");
}
}
}
You have compile errors in your code. You can't declare methods inside a another method. In your code You have override interface methods inside your main method. Take them out of the main method scope. Like this
public abstract class Mouse implements Hp {
char manufacturer;
char type;
static int scroll;
boolean click;
public static void main(String[] args){
}
public void scrollUp(int increment){
scroll = scroll + increment;
System.out.println("The mouse is scrolling up");
}
public void scrollDown (int decrement){
int scrollDown = scroll - decrement;
System.out.println("The mouse is scrolling down");
}
public void rightClick(){
boolean rightClick = true;
System.out.println("The mouse is right Clicking");
}
public void leftClick(){
boolean leftClick = true;
System.out.println("The mouse is left Clicking");
}
}
There are issues in your code. You can't declare another method inside a method.
Change your structure
public MyClass implements MyInterface{
public static void main(String[] args){
}
public void myMethod1(){
}
}
So you defined an Interface and an abstract class but no concrete class. Your implementation can't be used on it's own but requires a further 'implementation' class or you could remove the abstract keyword from your class definition. This keyword isn't needed as you don't have any abstract methods in your class.
Well and as others have pointed out, your main method (which you don't need) misses it's closing bracket.
Before Learning the concept of interface , You should have to learn basic . i.e you cannot have methods implemented inside another method, And to Know about interface first you should have knowledge about what is Abstract and Concrete.
ABSTRACT CLASS
public abstract class GraphicObject {
// declare fields
// declare nonabstract methods
abstract void draw();
}
An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.
An abstract method is a method that is declared without an implementation.
CONCRETE CLASS
An abstract class is meant to be used as the base class from which other classes are derived. The derived class is expected to provide implementations for the methods that are not implemented in the base class. A derived class that implements all the missing functionality is called a concrete class .
public class Graph implements GraphicObject{
public void draw()
{
//defination
}

Extended class and static variable

I've DynamicObject, Player, Enemy classes
public class DynamicObject {
protected static float speed;
}
public class Player extends DynamicObject {
/*some code*/
Player.speed = 100;
}
public class Enemy extends DynamicObject {
/*some code*/
Enemy.speed = 50;
}
And always speed value is overridden. Of course I can create new speed variable in Player and Enemy, but then the existing DynamicObject class is pointless. I want to have different speed values on each class. All objects of current class will have the same speed. How I should make it in correct way?
The speed variable should not be static. Otherwise it won't be bound to any of the instances of the DynamicObject class, nor any of it's subclasses instances.
If you want to have a different speed value for each of the subclasses, you can do:
public class DynamicObject {
protected float speed;
public DynamicObject(float speed) {
this.speed = speed;
}
public float getSpeed() {
return this.speed;
}
}
public class Player extends DynamicObject {
/*some code*/
public Player(float speed) {
super(speed);
}
}
public class Enemy extends DynamicObject {
/*some code*/
public Enemy(float speed) {
super(speed);
}
}
If every DynamicObject has a speed, and the speed is the same for every instance of, for example, Player, then you should have
public abstract int getSpeed();
in DynamicObject, and
#Override
public int getSpeed() {
return 100;
}
in Player.
If you need to have access to the constant speed returned for evry instance of Player without instantiateing a Player, just use
public static final int CONSTANT_PLAYER_SPEED = 100;
#Override
public int getSpeed() {
return 100;
}
and use Player.CONSTANT_PLAYER_SPEED to access the speed of all players.
Remove the static from that variable, if a variable is static, it's belong to the class, not to instances.
And making a static variable protected doesn't make any scene, since, inheritance and static are totally different.
protected float speed;
You could also have an abstract method, which would mean that you would always have to override it in your sub classes.
public abstract class Dynamic {
protected float speed;
abstract void setSpeed();
}
public class Player extends Dynamic{
#Override
void setSpeed() {
this.speed=50;
}
}

Creating multiple subclass objects

I'm trying to achieve a 'wave' of enemies through a for loop. Basically when a wave object is called it accepts an int that sets the number of enemies in the wave. Each enemy has it's own class that is a subclass of 'Enemy'. What I'm stuck on is how I can go about passing in a second parameter in the wave constructor to set which enemy subclass is created eg 25 'Orcs' created or 13 'Trolls' in one method. Any help will be greatly appreciated.
It sounds like you want to create a static factory method of the Enemy class that creates new Enemy objects based on parameter. Something like:
// EnemyType is an enum
public static Enemy createEnemy(EnemyType enemyType) {
switch (enemyType) {
case BASIC_MONSTER:
return new BasicMonster();
case ORC:
return new Orc();
case TROLL:
return new Troll();
case ..... // etc...
}
}
Note, I would use something cleaner for the parameter such as an enum, not an int so as to be sure that the parameter passed in is correct. Otherwise you risk having a nonsense int such as -24232 being passed in.
You can use an Enum
public enum EnemyType {
ORC{
#override
public Enemy create() {
return new Orc();
}
},
TROLL{
#override
public Enemy create() {
return new Troll();
}
}...etc;
public abstract Enemy create();
}
Then pass the relevant enum into your wave method:
public Collection<Enemy> createWave(final int num, final EnemyType enemyType) {
final Collection<Enemy> enemies = new ArrayList<>(num);
for(int i=0;i<num;i++) {
enemies.put(enemyType.create());
}
return enemies;
}
If you have lots of differenet enemy types consider a generic factory
public interface EmemyFactory<E extends Enemy> {
E create();
}
Then create an implementation for each enemy type and store them in the enum instead
public enum EnemyType {
ORC(new OrcFactory()),
TROLL(new TrollFactory()),
...etc;
private final EnemyFactory enemyFactory;
public EnemyType(final EnemyFactory enemyFactory) {
this.enemyFactory = enemyFactory;
}
public Enemy create() {
return enemyFactory.create();
}
}
And last and least you could use a little reflection, assuming your Enemies have a noargs constructor:
public Collection<Enemy> createWave(final int num, final Class<? extends Enemy> enemyClass) {
final Collection<Enemy> enemies = new ArrayList<>(num);
for(int i=0;i<num;i++) {
enemies.put(enemyClass.newInstance());
}
return enemies;
}
This is messy and prone to runtime errors however...

Categories