Why won't this class compile?
class Exam {
private int score;
// constructor initializes score to 99
public void Exam() {
score = 99;
}
// returns the current value of score
private int getScore() {
return score;
}
// returns the String representation of the Object
public String toString() {
return "The score is " + getScore();
}
}
Your constructor shouldn't have a return type. Not even void.
public Exam() {
score = 99;
}
A construct should not contain the void keyword:
public Exam() {
score = 99;
}
A constructor returns a reference the the newly created object. But you don't have to write it. So thinking it is void is wrong as well.
Constructors don't need return types. Remove void and you should be set.
In a constructor you don't use void.
Write the constructor as:
public Exam() {
score = 99;
}
The main problem is the missing package declaration.
package yourpkg;
class Exam {
Additionally, the return type on the for Exam() makes it a function instead of a constructor and will result in a warning.
Just a suggestion not related to the concrete problem:
private int score;
// returns the current value of score
private int getScore() {
return score;
}
There is no point in having that getScore() if your going to keep it private. Make it public.
Also, always use the #Override annotation whenever your intention is to override some method. Compiler will let you known in case you are failing to do so. That means bug prevention.
e.g.
// returns the String representation of the Object
#Override
public String toString() {
return "The score is " + getScore();
}
Related
In Java, getting this error:
Error: The constructor MyComplex(MyComplex) is undefined
Java Code:
public class MyComplex {
int realPart, imaginaryPart;
public MyComplex(){
}
public MyComplex(int realPart, int imaginaryPart) {
this.realPart = realPart;
this.imaginaryPart = imaginaryPart;
}
public void setRealPart(int realPart) {
this.realPart = realPart;
}
public String toString() {
return realPart + " + " + imaginaryPart +"i";
}
}
public class MyComplexTester {
public static void main(String[] args) {
MyComplex a = new MyComplex(20, 50);
MyComplex b = new MyComplex(a); //Error happens here
b.setRealPart(4);
System.out.println(b);
}
}
The code works fine if I use
MyComplex b = a;
But I can't change the code in the main method since its a homework on designing the class to run the given method.
Explanation
You do not have a constructor that accepts another MyComplex (copy constructor). You only created constructors that accept:
No argument, new MyComplex()
Two int arguments, new MyComplex(5, 2)
Solution
You need to explicitly define constructors that you want to use. Java does not generate such a constructor for you. For example:
public MyComplex(MyComplex other) {
realPart = other.realPart;
imaginaryPart = other.imaginaryPart;
}
Then it will also work.
Notes
In order to increase readability of your code, you should use explicit constructor forwarding for the new copy constructor and especially for your default constructor.
As an example, right now your default constructor new MyComplex() will lead to a complex value of 0 + 0i. But this can easily be overseen since your code does not clearly indicate that.
With forwarding, the intention is much clearer:
public MyComplex() {
this(0, 0);
}
public MyComplex(MyComplex other) {
this(other.realPart, other.imaginaryPart);
}
Then both will just forward to the explicit constructor that accepts the two int values.
Note that the only constructor Java auto-generates for you is the trivial default constructor. That is public MyComplex() { } (no arguments - does nothing). And only if you did not write any constructor yourself.
You should create the corresponding (copy) constructor.
So:
public MyComplex(MyComplex a){
realPart = a.realPart;
imaginaryPart = a.imaginaryPart;
}
you must have an overloaded constructor that accepts an object of type MyComplex to get this working.
below is your updated class
public class MyComplex {
int realPart, imaginaryPart;
public MyComplex(){
}
public MyComplex(int realPart, int imaginaryPart) {
this.realPart = realPart;
this.imaginaryPart = imaginaryPart;
}
public MyComplex(MyComplex mycomplex) {//this is the constructor you need
this.realPart = mycomplex.realPart;
this.imaginaryPart = mycomplex.imaginaryPart;
}
public void setRealPart(int realPart) {
this.realPart = realPart;
}
public String toString() {
return realPart + " + " + imaginaryPart +"i";
}
}
Because there is no constructor declared with MyComplex as argument. You need to declare the below constructor :-
public MyComplex(MyComplex mycomplex) {
this.realPart = mycomplex.realPart;
this.imaginaryPart = mycomplex.imaginaryPart;
}
Because in below line
MyComplex b = new MyComplex(a);
you are passing a which is of type MyComplex, but in MyComplex class you defined constructor with one parameter whose type is int. please correct your passing parameter.
This is my first time using enum in a class. I want to create a Pizza class so the user can create a Pizza object and then set the size, get the size, set the number of cheese etc.. Pizza() is the default constructor to initialize a Pizza object with no arguments. Thanks!!
package PizzaPackage;
public class Pizza {
private enum PizzaSize {
small, medium, large }
protected int numcheese;
protected int numpep;
protected int numham;
Pizza(){
PizzaSize newpizza= PizzaSize.medium; //Is this correct?
numcheese = 1;
numpep =0;
numham=0;
}
public int getnumcheese() {
return this.numcheese;
}
public int getnumpep() {
return this.numpep;
}
public int getnumham() {
return this.numham;
}
public void setSize(PizzaSize newpizza){
//???
}
public PizzaSize getSize(){
//???
}
}
Not quite.
PizzaSize is an enum, and you have declared that properly.
However, you are mistakening that PizzaSize enum for an instance member that holds this value for any particular instance of a Pizza.
You should create an additional private member variable, called private pizzaSize, and your constructor should be doing
this.pizzaSize = PizzaSize.medium;
Then, in your getSize() method, you should be returning this.pizzaSize;
Additionally, your setSize(PizzaSize newpizza) should contain this.pizzaSize = newpizza
Although you have created Enum, you forgot to have it as a instance member just like your other instance members numcheese, numpep etc.
PizzaSize newpizza;
Declare that as a member and use it.
package PizzaPackage;
public class Pizza {
private enum PizzaSize {
small, medium, large }
protected int numcheese;
protected int numpep;
protected int numham;
PizzaSize newpizza;
Pizza(){
newpizza= PizzaSize.medium; //Is this correct?
numcheese = 1;
numpep =0;
numham=0;
}
public int getnumcheese() {
return this.numcheese;
}
public int getnumpep() {
return this.numpep;
}
public int getnumham() {
return this.numham;
}
public void setSize(PizzaSize newpizza){
this.PizzaSize newpizza = newpizza;
}
public PizzaSize getSize(){
return newpizza;
}
}
//Is this correct?
Pizza(){
PizzaSize newpizza= PizzaSize.medium; //Is this correct?
numcheese = 1;
numpep =0;
numham=0;
}
Not really. Because you are restricting the scope of your PizzaSize to this constructor only. That variable of type PizzaSize no more accessible outside of constructor.
There are 2 possible solutions:
change type of your pizzasize field to PizzaSize
use ordinal method of enum values: pizzasize = newpizza.ordinal(); - it returns index of enum value in original enum.
I have the following:
Class 1:
public class SellProduct
{
private int productCost;
public SellProduct(int productCost)
{
this.productCost = productCost;
}
public int getProductCost()
{
return productCost;
}
}
This class will set how much a product costs.
Class 2:
public class SalesOfTheYear
{
private int totalIncome;
SellProduct sellProduct;
public SalesOfTheYear()
{
totalIncome = 0;
}
public void cashOut()
{
totalIncome = sellProduct.getProductCost() + totalIncome;
}
public int getSalesOfTheYear()
{
return totalIncome;
}
}
Now what I want is that class two to take how much the products cost and then set it to the totalIncome field. And of course to keep it's value at the same time and not replace it with a new totalIncome value.
However, every time I run cashout it sends a java.lang.NullPointerException. Does this mean I have to create an object of class sellPoduct?
And if do I would have to supply it with a parameter does that mean that whatever I supply it with a parameter so will it always be the productCost?
Yes, it makes sense to pass product cost to cashOut() method and add it into totalIncome rather than storing reference of SellProduct itself. It will look like this:
public void cashOut(int cost){
totalIncome += cost;
}
Also, we don't need default constructor in SalesOfTheYear class as int literals are assigned default values (0 in this case) when object is created.
Yes in Java whenever you have your own classes like SellProduct you will have to initialise it with:
SellProduct sellProduct = new SellProduct(xxx);
with xxx being an integer in your case
If you give it the number 20 then your totalIncome will increase with 20 every time you run cashOut()
To update the totalIncome field in a SalesOfTheYear instance, you need to transmit all required SellProduct instances to SalesOfTheYear .
Either, you have all the instances and you provide them in one time, either you may provide instance by instance.
public class SalesOfTheYear
{
private int totalIncome;
SellProduct sellProduct;
public SalesOfTheYear()
{
totalIncome = 0;
}
public void cashOut(SellProduct sellProduct)
{
totalIncome = sellProduct.getProductCost() + totalIncome;
}
public void cashOut(List<SellProduct> sellProducts)
{
for (SellProduct product : sellProducts){
cashOut(product);
}
}
public int getSalesOfTheYear()
{
return totalIncome;
}
}
How to use :
SalesOfTheYear salesOfTheYear = new SalesOfTheYear();
salesOfTheYear.cashOut(new SellProduct(500));
salesOfTheYear.cashOut(new SellProduct(100));
int totalSale = salesOfTheYear.getSalesOfTheYear();
BaseExample Class (I am not allowed to make the variable protected on this example):
public class BaseExample {
private int a;
public BaseExample(int inVal) {
a = inVal;
}
public BaseExample(BaseExample other){
a = other.a;
}
public String toString(){
return String.valueOf(a);
}
}
DerivedExample Class:
public class DerivedExample extends BaseExample {
private int b;
public DerivedExample(int inVal1, int inVal2){
super(inVal2);
a = inVal2;
}
}
The super method worked. Now how would I call it if I am asked this:
**Returns a reference to a string containing the value stored in the inherited varible a followed by a colon followed by the value stored in b public String toString()**
I have tried this:
public String toString(){
int base = new BaseExample(b);
return String.valueOf(base:this.b);
}
If I put two returns, it would give me an error of unreachable code. And if I put a super inside the valueOf it doesn't work. And this doesn't work as well. How is this executed?
I think you misunderstood the requirement, you need to print a which is located in the parent class separated by a colon concatenated with b which is in the current class.
String.valueOf(base:this.b)
This is incorrect syntax, what you want is
super.toString() + ":" + this.b;
I need a bit of help here. so i have this. I was basically wondering when you create an array of object of a parent class, then change that object to a child class, can I access the methods of that child class and if not why. thanks for any help.
public class Racer {
private String name;
private int position;
// Constructor
public Racer()
{}
public Racer(String name)
{
this.name = name;
position = 0;
}
public String getName()
{
return name;
}
public int getPosition()
{
return position;
}
public void setPosition(int n)
{
position = n;
}
public void setName(String n){
this.name=n;
}
}
the child class
public class Spartiates extends Racer{
private int energy;
public Spartiates(){
super();
}
public Spartiates(String name){
setName(name);
setPosition(20);
energy=100;
}
public void setEnergy(int energy){
this.energy=energy;
}
public int getEnergy(){
return energy;
}
}
main class
public class demo{
public static void main(String[] args){
Racer [] player = new player[3];
for(int i=0; i<player.length; i++){
player[i] = new Spartiates();
}
System.out.println(player[1].getEnergy());
}
so here the problem the getEnergy method doesn't work so I was wondering why. If anybody can help it would be very much appreciated. thanks
This is discussed here:
Is it possible to call subclasses' methods on a superclass object?
Along with all the reasons why doing something like this is probably never a good idea :).
You'll have to cast it to an instance of the subclass. If you plan on having a mixed array of object instances you'd need to first check the type:
System.out.println(((Racer)player[1]).getEnergy());
You need either define the function in the superclass or cast the object to the subclass.
If you intend the array to hold ONLY elements of the subclass Spartiates, then declare it as such.
Otherwise, if it needs to hold objects of both type, there only way to do this is to check with instanceof.
if (player[1] instanceof Spartiates)
System.out.println(((Spartiates)player[1]).getEnergy());
else
// handle other types
The reason energy is 0 is because you are calling your empty (no arg) constructor:
player[i] = new Spartiates();
which does not initialize the energy variable (so it will be 0 by default). You only set the variable to 100 in the constructor which takes in a String, namely here:
public Spartiates(String name){
setName(name);
setPosition(20);
energy=100;
}
So either call that constructor in the for loop with some string as an argument, or call your setEnergy() setter with some value after creating the object with the empty constructor.
Also, this is wrong:
Racer [] player = new player[3];
It should read:
Racer [] player = new Racer[3];
or:
Racer [] player = new Spartiates[3];