Hey guys! I stumbled upon a brick wall with my code. Can someone please help me
ID: 3605553 • Letter: H
Question
Hey guys! I stumbled upon a brick wall with my code. Can someone please help me out with the TODO's and explain what are public constructors and non argument constructors? Thank you thank you!
code:
public class unknown {
// TODO Declare a private String member variable, named manufacturer
private String manufacturer;
// TODO Declare a private int member variable, named model
private int model;
// TODO Declare a private double member variable, named price
private double price;
// TODO Declare a public no-argument constructor (assigning the member variables with default values)
// TODO Declare a public constructor with given inputs
// TODO Return the value of the member variable manufacturer
Explanation / Answer
Hello,
In the following, I have completed the code for the rest of the TODOs and also explained the concept of constructors, access modifiers and non-args constructors.
Constructors
- These are the methods that are invoked when an object of the class in being created for the first time. Typically, you would initialize the member variable to default values in these methods.
Public Constructors
- The constructors (and so do other member methods in your class) can be specified with different "access modifiers" viz private, public or protected. These modifiers control who can invoke these methods.
in case of "public", any other object can invoke the method.
so when you use "public" for a constructor - you mean that anyone can create a new object for this class.
Non-argument constructor
- When you define methods in your class - if required, you can define arguments for these methods and in some cases, you may NOT need any arguments.
So in case of "non-argument" constructor - you do NOT define any arguments for the constructor method.
The completed code ---
(Please note: To indent code in Eclipse IDE, you can select the code in each of the java file press "Ctrl + A" and then "Ctrl + i". )
----------------------------------------------------
//unknown.java
public class unknown {
//Declare a private String member variable, named manufacturer
private String manufacturer;
//Declare a private int member variable, named model
private int model;
//Declare a private double member variable, named price
private double price;
//Declare a public no-argument constructor (assigning the member variables with default values)
public unknown() {
manufacturer = "";
model = 0;
price = 0.0d;
}
//Declare a public constructor with given inputs
public unknown(String varManufacturer, int varModel, double varPrice) {
manufacturer = varManufacturer;
model = varModel;
price = varPrice;
}
//Return the value of the member variable manufacturer
public String getManufacturer() {
return manufacturer;
}
}