I am trying to instantiate an object (created in a "EmptySea" subclass of "Ship" class) into another "Ocean" class to fill an array with "EmptySea" objects.
Error is "EmptySea cannot be resolved to a type."
Here is my Ocean class code:
public class Ocean {
// Instance variables.
public Ship[][] ships = new Ship[10][10];
public int shotsFired;
public int hitCount;
// Constructor.
public Ocean() {
shotsFired = 0;
hitCount = 0;
for (int row = 0; row < ships.length; row++) {
for (int column = 0; column < ships[row].length; column++) {
ships[row][column] = new EmptySea();
public abstract class Ship {
// Instance variables.
private int bowRow;
private int bowColumn;
private int length;
private boolean horizontal;
private boolean[] hit = new boolean[4];
// No constructor needed for Ship class.
// Methods (too many to show).
public class EmptySea extends Ship {
// Constructor.
EmptySea() {
length = 1;
}
// Inherited methods to define.
int getLength() {
return length = 1;
}
String getShipType() {
return "Empty";
}
#Override
boolean shootAt(int row, int column) {
return false;
}
#Override
boolean isSunk() {
return false;
}
#Override
public String toString() {
return "-";
}
}
The ships array has been properly declared as an instance variable in Ocean class. Basically, it is not letting me put the EmptySea() object (the code for the "Ship" class and its "EmptySea" subclass runs correctly).
Do I need to somehow reference the superclass in this case?
If there's an easier way to do it, I can't do it that way (this way is specified in assignment).
Learn about the difference between a static nested class and an instance nested class.
Some other SO question on the same.
Short term: declare your inner EmptySea class with static, then read/understand why - in brief, without static an EmptySea instance cannot be created outside the context of a Ship instance.
Related
I have to write a program that has a constructor without parameters. I created another short program as an example to show what I do not understand.
So I have a class with the main-method:
public class Dog {
public static void main(String[] args) {
CharacteristicsOfTheDog Dog1 = new CharacteristicsOfTheDog(20, 40);
System.out.println(Dog1.toString());
}
}
Now implemented another class:
public class CharacteristicsOfTheDog {
int size = 0;
int kilogram = 0;
public CharacteristicsOfTheDog(/*int size, int kilogram*/) {
// this.size = size;
// this.kilogram = kilogram;
}
public double getSize() {
return size;
}
public double getKilogram() {
return kilogram;
}
public String toString() {
return "The Dog is " + getSize() + " cm and " + getKilogram() + " kg";
}
}
In the class "CharacteristicsOfTheDog" in "public CharacteristicsOfTheDog()" I removed the parameters by commenting them out. So the Problem is: if I remove the parameters the program does not work:/ but my task is to do this without the parameters (as far as I understood). Can someone help me please?
Keep your no-arg constructor and then add setters for your properties:
public class CharacteristicsOfTheDog {
int size = 0;
int kilogram = 0;
public CharacteristicsOfTheDog() {
}
public void setSize(int size){
this.size = size;
}
public void setKilogram(int kilogram){
this.kilogram = kilogram;
}
}
In your other class, call:
CharacteristicsOfTheDog dog1 = new CharacteristicsOfTheDog();
dog.setSize(20);
dog.setKilogram(40);
As a suggestion, the naming of your class as CharacteristicsOfTheDog is rather literal and stating the obvious. Properties and methods of a class are what describes the characteristics of a class in terms of it's properties and behavior. If you just name your class Dog, that would be perfect. No need to state the obvious.
Unless CharacteristicsOfTheDog is a subclass or you have a constructor with parameters, you don't need an empty constructor. Just omit it. The following works just fine.
If the parent class has a constructor with arguments, then the parent class will need an explicit empty constructor, but the following should still work.
CharacteristicsOfTheDog cotd = new CharacteristicsOfTheDog();
cotd.setKilogram(100);
}
class CharacteristicsOfTheDog {
int size = 0;
int kilogram = 0;
public void setSize(int size){
this.size = size;
}
public void setKilogram(int kilogram){
this.kilogram = kilogram;
}
}
Depending on your use case, you might want to make the Characteristics class an interface and implement it.
I am studying the inheritance (Java), and I wrote the following code. The first part is the CarBase, and then I created a childclass 1, called Bus.
My idea is that first make a judgement if it is a bus, and by doing that, I need a boolean [if(isBus)], but when I wrote this code in Eclipse, there is a error message, said 'isBus can not be resolved to a variable'.
Could some one please tell me how to solve this problem? Do I need to declare the boolean variable first?
Another question is about the declaration of local variables.
In the getOnBus(0 method, I have a local variable called temp,I was taught that whenever using a local variable insided a method, I need to declare it first and then I shall be able to use it, but I saw someone use it directly like the following, I was wandering what's the difference between the two?
public class Bus extends CarBase {
//Unique bus properties
public int max_Passenger = 35;
public int current_Passenger = 0;
// unique bus method
public boolean getOnBus(int p_amount) {
if(isBus) {
int temp = 0; // <===
temp = current_Passenger + p_amount; // <===
if( temp > max_Passenger) {
return false;
} else {
current_Passenger = temp;
return true;
}
}
return false;
}
}
or if there is difference if I use it without declaring it?
public class Bus extends CarBase {
//Unique bus properties
public int max_Passenger = 35;
public int current_Passenger = 0;
// unique bus method
public boolean getOnBus (int p_amount) {
if(isBus) {
int temp=current_Passenger+p_amount; // <====
if( temp > max_Passenger) {
return false;
} else {
current_Passenger = temp;
return true;
}
}
return false;
}
}
The code is as following
First Part CarBase(parent)
public class CarBase {
public int speed;
public String name;
public String color;
public int maxSpeed = 90;
// Method
public void speedUp(int p_speed) {
int tempSpeed = 0;
if (p_speed > 0) {
tempSpeed = speed + p_speed;
}
if (tempSpeed <= maxSpeed) {
speed =tempSpeed;
}
}
}
Second Part Bus (Child1)
public class Bus extends CarBase {
//Unique bus properties
public int max_Passenger = 35;
public int current_Passenger = 0;
// unique bus method
public boolean getOnBus (int p_amount) {
if (isBus) {
int temp = 0;
temp = current_Passenger + p_amount;
if (temp > max_Passenger) {
return false;
} else {
current_Passenger = temp;
return true;
}
}
return false;
}
}
The point in using inherance is to abstract whether an object is a Car or a Bus, and write code that works no matter what is passed. To do so, you use abstract methods. Consider
abstract class Vehicle {
private int occupied;
public Vehicle() {
occupied = 0;
}
public abstract int getCapacity(); // number of passengers
public boolean board(int howmany) {
if (occupied+howmany <= capacity) {
occupied += howmany;
return true;
}
else
return false;
}
public void unboard(int howmany) {
occupied -= howmany;
}
};
class Car extends Vehicle {
public Car () { super(); } // just call the Vehicle() constructor
public int getCapacity() { return 5; }
}
class Bus extends Vehicle {
public Bus() { super(); } // just call the Vehicle() constructor
public int getCapacity() { return 32; }
}
you'd write every function to accept a Vehicle, and deal with it without the need to know if it is a bus or a car. (the following is a dumb function, just to give you an example)
void board_on_first_avaible(Vehicle[] x, int n) {
for (int i=0; i<x.length; x++)
if (x.board(n))
return true; // board ok
return false; // couldn't board on anything
}
Note that you should design your code so that the functions are declared, abstract in Vehicle, for both Car and Bus. Thus getOnBus() would be a bad idea
OK for the first point "isBus" is not declared, i can not see the point of checking in this method as you already know u are extending the CarBase but if you need to check you can do it like this
if(this instanceof CarBase)
for the second point there is actually no effect for the change
int temp=0; // <===
temp= current_Passenger+p_amount; // <===
first you initialize with 0 then you assign the new value to it
int temp=current_Passenger+p_amount;
here you initialize the temp with the value
You don't need to check if the Bus object 'isBus()' .... it IS a Bus, because you are defining the class as Bus!
So... if you were to create a new Bus object, you would say something like:
Bus BigYellowBus0001 = new Bus();
if you were to then say:
BigYellowBus0001.getOnBus(10);
You would NOT need to check if BigYellowBus0001 is a bus.... right?
In fact, you don't even need to name the method getOnBus().... it could just be getOn.
I think maybe you've gotten off on the wrong foot by deciding that Bus is a subclass of Car.
As for local variables, this just means variable that begin and end inside the method... so you did that nicely with your 'temp' variable.
To show that you understand how to access variables of the superclass from the child class, you could check the speed of the bus before letting people on:
public boolean getOnBus (int p_amount){
if(speed = 0){
int temp=0;
temp= current_Passenger+p_amount;
if( temp > max_Passenger){
return false;
} else{
current_Passenger = temp;
return true;
}
}
return false;
}
isBus is not declared that reason why you got this error
You doesn't need this check, because this method declared for Bus class and you are sure what it IS a Bus not a parent CarBase class (please use Vechicle instead of CarBase, it's much better on my opinion)
In Java 0 is default value for int, so you don't need to init variable before assign new value
So you can simplify getOnBus() like that
public boolean getOnBus (int p_amount) {
int temp = current_Passenger + p_amount;
if (temp > max_Passenger) return false;
current_Passenger = temp;
return true;
}
To test if an object is an instance of a class you can to use variable instanceof YourClass which evaluates to a boolean
I'm trying to call a method from an abstract class Sprite in another package, but I got "The method getSymbol() is undefined for the type Sprite"
Here's the code.
public class ArrayGrid<Sprite> implements Grid<Sprite> {
private int numRows;
private int numColumns;
private Sprite[][] grid;
#SuppressWarnings("unchecked")
public ArrayGrid(int numRows, int numColumns) {
this.numRows = numRows;
this.numColumns = numColumns;
this.grid = (Sprite[][]) new Object[numRows][numColumns];
}
#SuppressWarnings("unchecked")
#Override
public boolean equals(Object other) {
if (this.getClass().equals(other.getClass())) {
if (this.numRows == ((ArrayGrid<Sprite>) other).numRows
&& this.numColumns == ((ArrayGrid<Sprite>) other).numColumns) {
for (int i = 0; i < this.numRows; i++) {
for (int j = 0; j < this.numColumns; j++) {
if (this.getCell(i, j).getSymbol() == ((ArrayGrid<Sprite>) other).getCell(i, j).getSymbol()) { // <<<<< the error is here
return true;
}
}
}
return true;
}
}
return false;
}
And here is the code from another package sprites
public abstract class Sprite {
protected char symbol;
protected int row;
protected int column;
public Sprite(char symbol, int row, int column) {
this.symbol = symbol;
this.row = row;
this.column = column;
}
public char getSymbol() {
return symbol;
}
I guess the problem is that the method from an abstract class cannot be instantiated.
But I don't know how to fix it.
This is the problem:
public class ArrayGrid<Sprite> implements Grid<Sprite>
The way you've declared the class, Sprite is the name of a type parameter. You've made this a generic class, and I suspect you didn't mean to. Within that class, Sprite refers to the type parameter, not the type - so you could have an ArrayGrid<String> which implemented Grid<String>... at which point you'd have a string array rather than a sprite array, so it's no wonder that getSymbol() wouldn't work, just as one symptom of the problem.
I suspect you just wanted:
public class ArrayGrid implements Grid<Sprite>
At that point, Sprite really refers to the type. And that means you can avoid the code that wouldn't work around arrays, and instead just write:
this.grid = new Sprite[numRows][numColumns];
Then there's no need to suppress the warnings :)
This is how my class definition goes:
public class ArrayBag implements Bag {
/**
* The array used to store the items in the bag.
*/
private Object[] items;
/**
* The number of items in the bag.
*/
private int numItems;
... and so on...
This is a method in the class definition, where a new object of this class is created inside the method:
//creates and returns an Arraybag that is the union of the called Arraybag and the parameter bag
public bag unionWith(Bag other) {
if (other == null)
throw new IllegalArgumentException();
int cap = this.capacity() + other.capacity();
//new object created here
ArrayBag newbag = new ArrayBag(cap);
for (int i = 0; i < numItems; i++) {
if (other.contains(items[i]))
newbag.add(items[i]);
}
for (int i = 0; i < newbag.numItems(); i++)
//Can I use "newbag.items[i]"?
if (numOccur(newbag.items[i]))
}
My question is, can I access the Object[] items of the newbag object from inside this method definition? Like this: newbag.items[i]
You can access it.
It is feasable to do:
public class AClass {
private int privateInteger;
public AClass() {
privateInteger = 5;
}
// First way
public void accessFromLocalInstance() {
AClass localInstanceOfClass = new AClass()
int valueOfLocalInstance = localInstanceOfClass.privateInteger;
}
// Second way
public void accessFromInstance(AClass instance) {
int valueOfInstance = instance.privateInteger;
}
}
because
"private" means restricted to this class, not restricted to this object.
See Access private field of another object in same class
I'm working on program/game where I have static utility class with params.
class ParamsGeneral {
public static final int H_FACTOR = 100;
public static int MAX_SCORE = 1000;
...
}
then I need to override this values in some specific cases, for example playing on map with limited score. So I did following:
class ParamsLimited extends ParamsGeneral {
public static int MAX_SCORE = 500;
// other params stay same
}
And the intended usage is following:
class Player {
ParamsGeneral par;
public Player() {
if(onLimitedMap()){
par = new ParamLimited();
}
}
public boolean isWinner() {
if(this.score == par.MAX_SCORE) {
return true;
}
return false;
}
}
I haven't actually tested this code, because IDE is complaining about calling static field through instance and also about field hiding. I clearly see that this code is stinks, so is there a way to achieve this or do I have to write each param class separately?
PS: I know I shoud make the default class abstract and use getters, I'm just curious if there is a way to make the values accesible statically.
You cannot override static members - in Java, neither methods nor fields could be overriden. However, in this case it does not look like you need to do any of that: since you have an instance of ParamsGeneral in the par variable, a non-static method would do what you need with the regular override.
class ParamsGeneral {
public int getMaxScore() {
return 1000;
}
}
class ParamsLimited extends ParamsGeneral {
#Override public int getMaxScore() {
return 500;
}
}
...
public boolean isWinner() {
// You do not need an "if" statement, because
// the == operator already gives you a boolean:
return this.score == par.getMaxScore();
}
I wouldn't use subclassing for a general game vs a limited game. I would use an enumeration, like:
public enum Scores {
GENERAL (1000),
LIMITED (500),
UNLIMITED (Integer.MAX_INT);
private int score;
private Scores(int score) { this.score = score; }
public int getScore() { return score; }
}
Then, when constructing a game, you can do:
Params generalParams = new Params(Scores.GENERAL);
Params limitedParams = new Params(Scores.LIMITED);
And so forth.
Doing it this way allows you to change the nature of your game while keeping your values centralized. Imagine if for every type of parameter you think of you have to create a new class. It could get very complicated, you could have hundreds of classes!
Simplest solution is to do this:
class ParamsGeneral {
public static final int H_FACTOR = 100;
public static final int MAX_SCORE = 1000;
public static final int MAX_SCORE_LIMITED = 500;
...
}
class Player {
int maxScore;
public Player() {
if(onLimitedMap()){
maxScore = ParamsGeneral.MAX_SCORE_LIMITED;
}
else {
maxScore = ParamsGeneral.MAX_SCORE;
}
}
public boolean isWinner() {
if(this.score == this.maxScore) {
return true;
}
return false;
}
}
No need to have an instance of ParamsGeneral, it is just a collection of static definitions for your game.
Have MAX_SCORE be private static with public static getters; then you can call ParamsGeneral.getMaxScore and ParamsLimited.getMaxScore and you'll get 1000 and 500 respectively