"Cannot instantiate the type...." - java

public class TestingClass {
public static void main(String[] args) {
int numberRooms = 6;
double totalSpace;
Room[] rooms = new Room[numberRooms];
rooms[0] = new Room(20, 20);
rooms[1] = new Room(20, 20);
rooms[2] = new Room(22, 20);
rooms[3] = new Room(20, 20);
rooms[4] = new Room(25, 20);
rooms[5] = new Room(15, 13);
Garage garage = new Garage(20, "Cement", 1, 20, 1, 4);
for (int i = 0; i < numberRooms; i++) {
totalSpace = totalSpace + calculateRoomSpace(rooms[i]);
}
System.out.println("Total room space is " + totalSpace);
foo(garage);
}
public static double calculateRoomSpace(Room roomSpace) {
double newRoomSpace = roomSpace.calcFloorSpace();
return newRoomSpace;
}
public static void foo(Building myBuilding) {
System.out.println("Total floor space is " + myBuilding.calcFloorSpace());
}
}
I put in this code and get the error
"Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Cannot instantiate the type Garage
at TestingClass.main(TestingClass.java:17)"
what is the problem here exactly?
Edit
** Here is the Garage class**
abstract public class Garage extends Building {
private int cars;
private String floorType;
private int garageLength;
private int garageWidth;
public Garage(int floors, int windows, int cars, String floorType,
int garageLength, int garageWidth) {
super(floors, windows);
this.cars = cars;
this.floorType = floorType;
this.garageLength = garageLength;
this.garageWidth = garageWidth;
}
#Override
public double calcFloorSpace() {
int floorSize;
floorSize = garageLength * garageWidth;
return floorSize;
}
public int getCars() {
return cars;
}
public void setCars(int cars) {
this.cars = cars;
}
public String getFloorType() {
return floorType;
}
public void setFloorType(String floorType) {
this.floorType = floorType;
}
public int getGarageLength() {
return garageLength;
}
public void setGarageLength(int garageLength) {
this.garageLength = garageLength;
}
public int getGarageWidth() {
return garageWidth;
}
public void setGarageWidth(int garageWidth) {
this.garageWidth = garageWidth;
}
#Override
public String toString() {
return "Garage [cars=" + cars + ", floorType=" + floorType
+ ", garageLength=" + garageLength + ", garageWidth="
+ garageWidth + "]";
}
}
Hope this helps. Not an expert at this and have spent quite a while figuring this out. thanks

You can't instantiate an abstract class.
You've got two options:
Remove abstract from the class declaration, or
Create another class to extend Garage, which can be instantiated.

You cannot instantiate an instance of an abstract class. You either need to make your class concrete (remove the abstract modifier on the class and provide an implementation for all methods), or extend the abstract class to create a non-abstract class.
When you remove the abstract modifier, the compiler will tell you what abstract methods you are missing (if any).

Your Garage Class is declared as abstract class cannot be instantiated .Check this for more details Can an abstract class have a constructor?

Garage is an abstract class, so it cannot be instantiated. Only its subclasses can be instantiated.

Related

Compilation error: constructor in class cannot be applied to given types

Im trying to create a subclass object using an enum from the super class but when I try to create the object in the subclass I get this error.
error: constructor Payroll in class Payroll cannot be applied to given types;
public PayClaim(int hours, PayLevel level){
^
required: PayLevel
found: no arguments
reason: actual and formal argument lists differ in length
1 error
This is my superclass Payroll
public class Payroll{
static double OVERTIME_RATE = 1.5;
static int REGULAR_WEEK = 40;
static int LEVEL_ONE_PAY = 15;
static int LEVEL_TWO_PAY = 25;
static int LEVEL_THREE_PAY = 40;
public enum PayLevel{
ONE, TWO, THREE
}
private PayLevel levels;
public Payroll(PayLevel levels){
this.levels = levels;
}
public PayLevel getPayLevel(){
return levels;
}
public static void main (String [] args) {
Payroll.OVERTIME_RATE = 1.75;
Payroll.REGULAR_WEEK = 40;
Payroll.LEVEL_ONE_PAY = 12;
System.out.println(Payroll.calculatePay(35, Payroll.PayLevel.ONE));
}
public static double calculatePay(int noHoursWorked, PayLevel level){
//do stuff
}
}
And this is my subclass PayClaim
public class PayClaim extends Payroll{
int noHoursWorked;
public Payroll.PayLevel payLevel;
double calculatedPay = 0;
public static void main (String [] args) {
PayClaim p = new PayClaim(1, Payroll.PayLevel.ONE);
System.out.println(p);
}
public PayClaim(int hours, PayLevel level){
if(hours > 80 || hours < 1){
throw new IllegalArgumentException();
}
else{
noHoursWorked = hours;
payLevel = level;
}
}
public int getNoHoursWorked(){
return noHoursWorked;
}
public PayLevel getPayLevel(){
return payLevel;
}
public double getClaculatedPay(){
return calculatedPay;
}
public void setCalculatedPay(double pay){
//
}
public String toString(){
//
}
My apologies if I missed something trivial its just that the code wont even compile so I'm really struggling to find just where I'm going wrong here.
I believe the answer you are looking for is very simple. If you invoke the parent constructor to the subclass, this should resolve the compilation problems. You can do this by using the following changes. The change I made is at the beginning of the constructor, it simply calls the parents constructor to create an object, since it is a subclass.
public class PayClaim extends Payroll{
int noHoursWorked;
public Payroll.PayLevel payLevel;
double calculatedPay = 0;
public static void main (String [] args) {
PayClaim p = new PayClaim(1, Payroll.PayLevel.ONE);
System.out.println(p);
}
public PayClaim(int hours, PayLevel level){
enter code here
super(level);
if(hours > 80 || hours < 1){
throw new IllegalArgumentException();
}
else{
noHoursWorked = hours;
payLevel = level;
}
}
public int getNoHoursWorked(){
return noHoursWorked;
}
public PayLevel getPayLevel(){
return payLevel;
}
public double getClaculatedPay(){
return calculatedPay;
}
public void setCalculatedPay(double pay){
//
}
public String toString(){
//
}

java method which can be changed

I'm a little unclear on how to make this method. it has to make a method called setCapacity that later can override. I have to "Modify the class Vehicle, the base class, to include a method called setCapacity which
allows the engine capacity to be changed"
class Vehicle {
void setCapactiy1 () {
int setCapactity == 0;
}
}
int capacity;
String make;
Vehicle(int theCapacity, String theMake) {
capacity = theCapacity;
make = theMake;
}
void print() {
System.out.println("Vehicle Info:");
System.out.println(" capacity = " + capacity + "cc" );
System.out.println(" make = " + make );
}
}
class Car extends Vehicle {
public String type;
public String model;
public Car(int theCapacity, String theMake, String theType, String theModel) {
super(theCapacity, theMake);
type = theType;
model = theModel;
}
#Override
public void print() {
super.print();
System.out.println(" type = " + type);
System.out.println(" model = " + model);
}
#Override
}
class Task2 {
public static void main(String[] args) {
Car car1 = new Car(1200,"Holden","sedan","Barina");
Car car2 = new Car(1500,"Mazda","sedan","323");
car1.print();
car2.print();
}
}
Seems like a basic setter... It should go like
public void setCapacity(int newCapacity) {
this.capacity = newCapacity;
}

Calling Parameters from parent constructor

How do you call the parents constructor and give the parent constructor a parameter of 50? I need to make a constructor for HoldenDB which as no formal parameter and calls its parents constructor.
I have started by extending HoldeDB to VechicleDB, however, I'm unsure how to proceed for there.
If someone could help me that would be much appreciated.
import java.util.ArrayList;
class Vehicle {
int capacity;
String make;
void setCapacity(int setCapacity) {
this.capacity = setCapacity;
System.out.println("New Capacity = " + setCapacity);
}
Vehicle(int theCapacity, String theMake) {
capacity = theCapacity;
make = theMake;
}
void print() {
System.out.println("Vehicle Info:");
System.out.println(" capacity = " + capacity + "cc" );
System.out.println(" make = " + make );
}
}
class Car extends Vehicle {
public String type;
public String model;
public Car(int theCapacity, String theMake, String theType, String theModel) {
super(theCapacity, theMake);
type = theType;
model = theModel;
}
#Override
public void print() {
super.print();
System.out.println(" type = " + type);
System.out.println(" model = " + model);
}
#Override
public void setCapacity(int setCapacity) {
System.out.println("Cannot change capacity of a car");
}
}
class VehicleDB {
ArrayList<Vehicle> db = new ArrayList<Vehicle>();
void addVehicle(Vehicle c){
db.add(c);
}
void print(){
System.out.println("=== Vehicle Data Base ===");
for(Vehicle v: db){
v.print();
}
}
}
class HoldenDB extends VehicleDB {
void addCar(Vehicle c){
db.add(c);
}
}
class Task5 {
public static void main (String[]args){
HoldenDB db = new HoldenDB ();
db.addCar(1200,"sedan","Barina");
db.addCar(3800,"wagon","Commodore");
db.print();
}
}
public class VehicleDB {
private int n;
public VehicleDB(int n) {
this.n = n;
}
}
public class HoldenDB extends VehicleDB {
public HoldenDB() {
super(50);
}
}

make a global object in java

I want to make an array of objects and use it in different functions. I wrote this pseudocode
privat stock[] d;
privat stock example;
public void StockCheck(){
d =new stock[2];
d[0]= new stock("a","test1", 22);
d[1]= new stock("b","test2", 34);
}
#Override
public stock getStock(String name) throws StockCheckNotFoundException{
int i;
System.out.println("ok" + name + d.legth); // error
example = new stock("example","example",2);
return example;
}
In class test I make an instance of getStock and I call the function getStock stock.getStock();
I get a NullPointerExeption when I do d.length. d is null but I don't understand why.
Hmmmm. If that is in any way like your real code, then the problem is that your "constructor" isn't really a constructor, as you've declared it to return void, making it an ordinary method instead. Remove tbat "void" and it may fix the problem!
Perhaps this example of code will do what you need, using three classes
Test - the main test code
Stock - the implied code for Stock from your question
StockCheck - the corrected code from your question.
(Note: you may really want to use an ArrayList inside StockQuote so you can add and delete Stocks.)
Test class
package stackJavaExample;
public class Test {
public static void main(String[] args) {
String[] testNames = {"test1","test2","notThere"};
StockCheck mStockCheck = new StockCheck();
for (int i=0; i<testNames.length; i++) {
Stock result = mStockCheck.getStock(testNames[i]);
if (result == null) {
System.out.println("No stock for name: " + testNames[i]);
} else {
System.out.println("Found stock: " + result.getName() + ", " + result.getSymbol() + ", " + result.getValue());
}
}
}
}
Stock class
package stackJavaExample;
public class Stock {
private String symbol;
private String name;
private double value;
public Stock(String symbol, String name, double value) {
this.symbol = symbol;
this.name = name;
this.value = value;
}
public String getSymbol() { return symbol;}
public String getName() { return name;}
public double getValue() {return value;}
}
StockCheck class
package stackJavaExample;
public class StockCheck {
private Stock[] d;
public StockCheck() {
d = new Stock[2];
d[0] = new Stock("a","test1", 22);
d[1] = new Stock("b","test2", 34);
}
public Stock getStock(String name) {
for (int i=0; i < d.length; i++) {
if (d[i].getName().equalsIgnoreCase(name)) {
return d[i];
}
}
return null;
}
}

Cannot Find Symbol Method Error

I have an assignment from my Java 1 class (I'm a beginner) and the question instructs us to make some code more object-oriented. I've done what I can for the assignment, but one of my files consistently gives me a Cannot Find Symbol Method error even though the files are in the same project. I know the methods are there, so what's going on? The error only occurs in AlienPack, which doesn't seem to recognize the other files, all of which are in the same project (including AlienPack). The getDamage() method that's being called in AlienPack isn't being found (it's in SnakeAlien, OgreAlien, etc).
EDIT: The new error for the getDamage() methods I'm trying to invoke in AlienPack is that the methods still aren't being found. AlienDriver can't find calculateDamage() either.
Here's the code I've got so far:
Alien:
public class Alien {
// instance variables
private String name;
private int health;
// setters
public void setName(String n) {
name = n; }
public void setHealth(int h) {
if(h>0&&h<=100) {
health = h;
} else {
System.out.println("Error! Invalid health value!");
System.exit(0); } }
// getters
public String getName() {
return name; }
public int getHealth() {
return health; }
// constructors
public Alien() {
setName("No name");
setHealth(100); }
public Alien(String n, int h) {
setName(n);
setHealth(h); }
public Alien(Alien anAlien) {
setName(anAlien.getName());
setHealth(anAlien.getHealth()); }
public Alien clone() {
return new Alien(this);
} }
SnakeAlien:
public class SnakeAlien extends Alien { // new file
// instance variables
private int damage;
// setters
public void setDamage(int d) {
if(d>0) {
damage = d;
} else {
System.out.println("Error! Invalid damage value!");
System.exit(0); } }
// getters
public int getDamage() {
return damage; }
// constructors
public SnakeAlien() {
super();
setDamage(0); }
public SnakeAlien(String n, int h, int d) {
super(n, h);
setDamage(d); }
public SnakeAlien(SnakeAlien anAlien) {
super(anAlien);
setDamage(anAlien.getDamage()); }
public SnakeAlien clone() {
return new SnakeAlien(this);
} }
OgreAlien:
public class OgreAlien extends Alien { // new file
// instance variables
private int damage;
// setters
public void setDamage(int d) {
if(d>0) {
damage = d;
} else {
System.out.println("Error! Invalid damage value!");
System.exit(0); } }
// getters
public int getDamage() {
return damage; }
// constructors
public OgreAlien() {
super();
setDamage(0); }
public OgreAlien(String n, int h, int d) {
super(n, h);
setDamage(d); }
public OgreAlien(OgreAlien anAlien) {
super(anAlien);
setDamage(anAlien.getDamage()); }
public OgreAlien clone() {
return new OgreAlien(this);
} }
MarshmallwManAlien:
public class MarshmallowManAlien extends Alien { // new file
// instance variables
private int damage;
// setters
public void setDamage(int d) {
if(d>0) {
damage = d;
} else {
System.out.println("Error! Invalid damage value!");
System.exit(0); } }
// getters
public int getDamage() {
return damage; }
// constructors
public MarshmallowManAlien() {
super();
setDamage(0); }
public MarshmallowManAlien(String n, int h, int d) {
super(n, h);
setDamage(d); }
public MarshmallowManAlien(MarshmallowManAlien anAlien) {
super(anAlien);
setDamage(anAlien.getDamage()); }
public MarshmallowManAlien clone() {
return new MarshmallowManAlien(this);
} }
AlienPack:
public class AlienPack { // new file, this one isn't recognizing the others
// instance variables
private Alien[] pack;
// setters
public void setPack(Alien[] aliens) {
pack = new Alien[aliens.length];
for(int i = 0; i<aliens.length; i++) {
pack[i]=aliens[i].clone(); } }
// getters
public Alien[] getPack() {
Alien[] temp = new Alien[pack.length];
for(int i = 0; i<pack.length; i++) {
temp[i]=pack[i].clone(); }
return temp; }
// constructors
public AlienPack() {
Alien[] nothing = new Alien[1];
nothing[0]=null;
setPack(nothing); }
public AlienPack(Alien[] aliens) {
setPack(aliens);}
// other methods
public int calculateDamage() {
int damage = 0;
for(int i = 0; i<pack.length; i++) {
if((new SnakeAlien()).getClass()==pack[i].getClass()) {
pack[i].getDamage() +=damage;
} else if((new OgreAlien()).getClass()==pack[i].getClass()) {
pack[i].getDamage() +=damage;
} else if((new MarshmallowManAlien()).getClass()==pack[i].getClass()) {
pack[i].getDamage() +=damage;
} else {
System.out.println("Error! Invalid object!");
System.exit(0); } }
return damage; } }
AlienDriver:
public class AlienDriver { // driver class
public static void main(String[] args) {
Alien[] group = new Alien[5];
group[0]= new SnakeAlien("Bobby", 100, 10);
group[1]= new OgreAlien("Timmy", 100, 6);
group[2]= new MarshmallowManAlien("Tommy", 100, 1);
group[3]= new OgreAlien("Ricky", 100, 6);
group[4]= new SnakeAlien("Mike", 100, 10);
System.out.println(group.calculateDamage());
} }
Two problems:
pack[i].getClass().getDamage() ...
should be just
pack[i].getDamage() ...
You seem to be confused about what the getClass() method does. It returns an object which represents the class (i.e. java.lang.Class) of another object. It is used for reflection. To invoke getDamage() you would just invoke it directly on pack[i] as shown above.
However...
You are attempting to invoke the method getDamage() using a reference of type Alien, which is a base class of all the concrete alien types. If you want to do it that way,
getDamage() needs to be declared abstract in the base class so it can be found and dispatched to the correct subclass when invoking it via an Alien reference.
In Alien:
public abstract class Alien {
...
public abstract int getDamage();
An alternative is to cast to the appropriate subclass at each point since you know what it is:
((SnakeAlien)pack[i]).getDamage() +=damage;
However (again) even that is wrong. You can't apply += to an "rvalue". What you need to do here is either:
Also declare setDamage() abstract in Alien and do pack[i].setDamage(pack[i].getDamage()+damage);
If casting, ((SnakeAlien)pack[i]).setDamage( ((SnakeAlien)pack[i].getDamage()) + damage);
My Recommendation:
In class Alien:
public abstract class Alien {
...
private int damage = 0; // Move damage up to the abstract base class
public int addToDamage(int n) { this.damage += n; }
...
}
In your driver, no need to test the class. Invoke the addToDamage() method on the Alien reference.
I think that at least part of your problem is the getClass() method. You are expecting it to return an object but it does not. Just call directly to the array.
pack[I].getDamage()
should work assuming that the correct type of object is stored in pack()

Categories

Resources