Why am I getting this error "The constructor is undefined"? - java

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.

Related

Super class is not passing along values

Super class is not functioning, as when the Steelfactory class try's to get the data from the super class, the output shows that there is noting there.
Looking to solves as to why this might be happening.
The Factory called null with 0makes cars at a rate of 0since the year 1998
I am wondering if it is due to, having called my super class wrong, but I did not gain any errors when writing it. Or could there there be another issue in the code logic wise?
The code:
package finalsproject;
static abstract class Factory {
//Atributes:
String factoryName; //The name of the factory
int employeeAmount; // number of workers in the factory
int producedAmount; // number of products made
// Constructor:
public Factory (String ifactoryName,int iemployeeAmount,int iproducedAmount) {// Prameterized consrtuctor
factoryName = ifactoryName;
employeeAmount = iemployeeAmount;
producedAmount = iproducedAmount;
}
//Methods:
public abstract String getFactoryName();
public abstract int getEmployeeAmount();
public abstract int getProducedAmount();
}
//The class SteelFactory must have the following specifications
//-It must implement the abstract class Factory
//Make these two classes implement the abstract class above
static class SteelFactory extends Factory {
//Attributes:
String factoryName; // Name of the factory
int employeeAmount; // Number of workers
int producedAmount; // number of products
int yearCreated; // the year the factory was made
//Constructor:
public SteelFactory (String ifactoryName,int iemployeeAmount,int iproducedAmount,int iyearCreated) {
super ( ifactoryName, iemployeeAmount,iproducedAmount);
yearCreated = iyearCreated;
}
// Methods
public String getFactoryName() {
return (factoryName);
}
public int getEmployeeAmount() {
return (employeeAmount);
}
public int getProducedAmount() {
return (producedAmount);
}
public String toString () {
return ("The Factory called " + factoryName + " with " + employeeAmount + "makes cars at a rate of " + producedAmount + "since the year "+ yearCreated);
}
}
You can resolve this by simply removing the duplicate variables factoryName, employeeAmount and producedAmount from your SteelFactory class, otherwise the class will use the local variables that were never initialized instead of the correct variables from the super class. One big reason for extending a class is so that we don't have to re-use/re-type the same variables and methods in multiple classes.
Also, don't forget to use #Override annotation, it helps you keep track of which methods have been extended and helps prevent common mistakes.
Working code as follows:
static class SteelFactory extends Factory {
//Attributes:
int yearCreated; // the year the factory was made
//Constructor:
public SteelFactory (String ifactoryName,int iemployeeAmount,int iproducedAmount,int iyearCreated) {
super ( ifactoryName, iemployeeAmount,iproducedAmount);
yearCreated = iyearCreated;
}
// Methods
#Override
public String getFactoryName() {
return (factoryName);
}
#Override
public int getEmployeeAmount() {
return (employeeAmount);
}
#Override
public int getProducedAmount() {
return (producedAmount);
}
#Override
public String toString () {
return ("The Factory called " + factoryName + " with " + employeeAmount + "makes cars at a rate of " + producedAmount + "since the year "+ yearCreated);
}
}
Then simply use:
SteelFactory test = new SteelFactory("Test", 78, 26, 2022);
System.out.println(test.toString());
Will correctly print the following result (You'll need to fix your formatting to include spaces):
The Factory called Test with 78makes cars at a rate of 26since the year 2022

The Constructor is undefined? Enum error

public Tipo getTipo() {
return this.Importo < 0.0 ? Tipo.USCITA : Tipo.ENTRATA;
}
public int compareTo(Movimento m) {
if (this.idConto != this.idConto) {
return this.idConto - this.idConto;
}
return this.DataMov.compareTo(this.DataMov);
}
public static enum Tipo {
ENTRATA,// here i have this error : The constructor Movimento.Tipo() is undefined
USCITA;// here is the same : The constructor Movimento.Tipo() is undefined
private Tipo(String string2, int n2) {
}
}
I already have constructor that I need, what else I need to write?
I am not sure how do you want to define enum. There are basically 2 solutions to this:
1. Define no parameter enum
public static enum Tipo {
ENTRATA,
USCITA;
}
2. Define enum with parameters
public static enum Tipo {
ENTRATA("Entrata", 1),
USCITA("Uscita", 2);
private String string;
private int integer;
private Tipo(String string, int integer) {
this.string = string;
this.integer = integer;
}
}
You wrote a constructor that takes two arguments, but no default constructor. That means the compiler will not provide a no-arg constructor. You should provide one or remove the private constructor.
I see no reason for the private constructor with two arguments. You don't have any private data members in your enum.
Why is your enum static? Remove that.
public enum Tipo {
ENTRATA, USCITA;
}
You are written wrong enum.
public enum abc {
ENTRATA("abc", 1),// here i have this error : The constructor Movimento.Tipo() is undefined
USCITA("xyz", 2);// here is the same : The constructor Movimento.Tipo() is undefined
private abc(String string2, int n2) {
}
}

.valueOf using another class's private variable

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;

How can I access a field of a local-inner class from another method?

Consider the field bar of the local-inner class MyValue:
public class C {
public static void main(String x[]) {
class MyValue implements IValue {
String bar = "bar";
public String getValue() {
return "my value";
}
}
MyValue myValue = new MyValue();
D d = new D();
d.accessBar(myValue);
}
}
which implements the IValue interface:
interface IValue {
public String getValue();
}
How can I access the field bar from another function (outside of main), let's say in class D:
class D {
public void accessBar(IValue value) {
String info = value.getValue() + value.bar;
}
}
If you need to access the pass key of a ship and you only have the IShip interface, then IShip should have a getPassKey() method, basically. Even if you could cast to ShipAddress within the method, you shouldn't do so - you should make the parameter type for the calculatedInfo method suitable for all the operations the method requires.
You could access it via reflection, but that would be horribly brittle and I'd strongly recommend that you don't do that.

what's wrong with my class definition?

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();
}

Categories

Resources