I have an abstract superclass with a constructor of the form
public classname(String name, int amount)
and want to create a subclass of that abstract class that instead of taking a String as its first parameter takes an integer value that represents a given String name, so e.g. 0 stands for some String, 1 for another and so on.
When I try to write a constructor of the form subclass(int number, int amount) I get an error of the form "implicit super constructor is undefined. Must explicitly invoke another constructor."
Why is it not possible to create another, different constructor in the subclass?
Wrong question, you can write another constructor in the subclass, but as the super class has no default/no-argument constructor, you have to explicitely call the constructor of the super class you mentioned to ensure the invariance of the super class.
As mentioned by others in derived class you need to invoke constructor of its super class using super(arguments). Also this call must be first instruction in your constructor so you will probably face problem where you will need to determine value you want to place as name before calling constructor like
MyClass(int id, int amount){
super("???",amount);
}
here we don't know yet what value to use in place of "???". Unfortunately you can't use
MyClass(int id, int amount){
if (id==1) super("foo",amount);
else super("bar",amount);
}
One of possible solutions is to create separate method which will return correct name based on id and use it as super parameter like
MyClass(int id, int amount){
super(choseName(id),amount);
}
private static String choseName(int id){
if (id==1)
return "foo";
else
return "bar";
}
One solution is to use static factory methods. Consider this:
public abstract class Amount
{
protected static final List<String> IDENTIFIERS
= Arrays.asList("idfor0", "idfor1" /* etc */);
protected final String identifier;
protected final int amount;
public static Amount forIdentifierNumber(final int number, final int amount)
{
return new IdBasedAmount(IDENTIFIERS.get(number), amount);
}
protected Amount(final String identifier, final int amount)
{
this.identifier = identifier;
this.amount = amount;
}
}
Then, in the same package:
final class IdBasedAmount
extends Amount
{
IdBasedAccount(final String identifier, final int amount)
{
super(identifier, amount);
}
}
Call from code:
final Amount amount = Amount.forIdentifierNumber(0, 20100);
After that, it is only a matter of defining whatever methods are needed in the Amount class (either final or delegated to subclasses).
Of course, adapt to your code.
Edit: an example of static factory methods yielding classes with different internal state but the same behaviour: here. SchemaKey is abstract, acts as an "interface" and has static factory methods within itself to generate concrete classes.
You need to call super() in your subclass's constructor and hence explicitly call the super class's constructor.
Related
I'm creating a new class which is vehicle. I'm expecting the only protected variables inherit to subclasses. But when I try to create Constructor with IDE, it is also using superclasses private variables? -Which is private String vehicleName- I'm not clearly understanding this situation. Shouldn't I use auto Concstructor?
public class Vehicle {
protected int capacityOfPassengers;
protected String mapOfRoute;
private String vehicleName;
public Vehicle(int capacityOfPassengers, String mapOfRoute,
String vehicleName) {
this.capacityOfPassengers = capacityOfPassengers;
this.mapOfRoute = mapOfRoute;
this.vehicleName = vehicleName;
}
}
public class LandVehicle extends Vehicle {
private String brand;
private int priceModel;
public LandVehicle(int capacityOfPassengers, String mapOfRoute,
String vehicleName, String brand, int priceModel) {
super(capacityOfPassengers, mapOfRoute, vehicleName);
this.brand = brand;
this.priceModel = priceModel;
}
}
Generally, a class has a default constructor, taking no arguments, IF no constructor has been provided by you.
When you subclass Vehicle with your LandVehicle, your LandVehicle is a type of Vehicle. This means that it inherits methods and field from its superclass, even if they are private. For the class LandVehicle these members are just not visible, but they are still present - otherwise it couldn't function properly. The private keyword is an access modifier, that changes visibility to the caller.
As a result, to instantiate a LandVehicle, you also must provide the required attributes of its superclass Vehicle (since there is no default, no-arg constructor in Vehicle). In your example, a LandVehicle without a name (from Vehicle) wouldn't make sense, since a LandVehicle is a Vehicle, which requires a name.
You cannot access vehicleName from LandVehicle. You just pass some string parameter to super constructor, and the super constructor sets the vehicleName. For example, you can't initialize this field inside LandVehicle class as this.vehicleName = vehicleName.
I am trying to learn Java by my self and i am making a game you all properly know, which is Monopoly.
I have searched for my answer but couldnt find it, so here it is.
I have a class Field with two variables fieldnumber and fieldname. My idea is to make a field with a number, so the program know where the players are (not relevant now).
The fieldname and fieldnumbershould only be readable (means not editable) after the program have created the fields and names for the fields.
I need to know how i can intialize these two variables into a contructor and make the variables to be only "getters", so they cant be changed later on.
(obs: the class Field is only a subclass, i need to use the data in the main class later on)
Im a bit confused and tried to read the book i am using, but no luck.
Declare the fields final, assign them in constructor and do not write setters.
Should the number of properties increase, you may consider using builder pattern to avoid constructor with many arguments.
class Field {
private final int fieldNumber;
private final String fieldName;
public Field(final int fieldNumber, final String fieldName) {
// you may validate the values here and throw exception in case of non-valid values
this.fieldNumber = fieldNumber;
this.fieldName = fieldName;
}
public int getFieldNumber() {
return fieldNumber;
}
public String getFieldName() {
return fieldName;
}
}
I suggest to make the two attribut as private (not accessible), initialize them when creating the instance, and you can use the getter to get their values:
class Field{
private String fieldname;
private int fieldnumber;
public Field (String fieldname, int fieldnumber)
{
this.fieldname = fieldname;
this.fieldnumber= fieldnumber;
}
public String getFieldname(){
return fieldname;
}
public int getFieldnumber(){
return fieldnumber;
}
public String toString(){
return fieldnumber+ " " +fieldname;
}
public boolean equals(Object obj){
Field field = (Field) obj;
return (fieldnumber == field.fieldnumber && fieldname.equals(field.fieldname);
}
}
A "getter" is a method that returns the value of your field.
A "setter" is a method typically taking one argument, setting the value of your field (possibly after some validation).
For good encapsulation, your instance fields should typically only be accessed within the maximum scope allowed within context (typically private fields with getters/setters, sometimes protected or package-protected fields when inheritance or more complex settings are required)
A field marked with the final non-access modifier can only be assigned once
In your case, if the fields are scoped within the instance of your class, but will never change once assigned, you can mark them final and assign them in a constructor or instance statement (no setters).
If they are not bound to an instance, but rather to the class, then you can mark them constant (static final) and assign them right away (you can then safely make them public if they are immutable - i.e. Strings or primitives)
Getter means a method that returns a value an object stores. A variable being a getter doesn't mean anything. Getters are usually used to get variables that are declared private; that is, variables that are not 'visible' from outside the class. See the example:
class Example {
private int value;
public Example(int valueToBeSet) {
this.value = valueToBeSet;
}
}
In the above example, the variable value is only visible from the class Example; any other class cannot get that variable. This is useful when you want that no other class is able to change its value. However, to get the value from the object, you use a getter:
class Example {
private int value;
public Example(int valueToBeSet) {
this.value = valueToBeSet;
}
public int getValue() {
return this.value;
}
}
Here the method getValue() is a getter. You cannot change the value, because it is private, but you can call the method getValue(), and get the value, because the method is public.
Other way to assign a variable's value, be able to get its value, but not be able to change it, is to use the final keyword:
class Example {
public final int value;
public Example(int valueToBeSet) {
this.value = valueToBeSet;
}
}
This way the variable's value can only be set once, in the constructor, and never again. However, you can still get the value from outside the class because it is public. This is often a good way to do things, however it has its downsides; namely as I explained, you cannot change the value anymore, and to get an object with a different value, you would have to create a new object altogether. This is the closest you can get to a "getter variable".
I have a class like this
public class User implements UserInterface, Parcelable
{
public User(int userID, String firstName, String lastName, String mobileNumber, Date dateAccountCreated)
{
this.userID = userID;
this.firstName = firstName;
this.lastName = lastName;
this.mobileNumber = mobileNumber;
this.dateAccountCreated = dateAccountCreated;
}
}
And I then have another class that extends into this:
public class Invitee extends User
{
private int eventDescision;
public Invitee(User u, int eventDescision)
{
super() = u;
this.eventDescision = eventDescision;
}
}
Obviously this line super() = u; does not work. However, how can I achieve the this functionality where I pass the User object the invitee recieves and set it as the extended object without having to create another constructor? I know I can just the object as a variable with a getter and setter, however, I like the way it flows without doing this as and invitee is always user.
User you receive in Invitee constructor is a real instance and you are creating another one. You can not assign one instance in a super constructor, you only can copy it, with a copy constructor.
It should rather be:
super(u.getUserID(),
u.getFirstName(),
u.getLastName(),
u.getMobileNumber(),
u.getDateAccountCreated());
You cannot automatically pass an instance of the base class to the base class' constructor call (super) in the child class' constructor.
What you might want to do is pass the base class' properties in the super call.
For instance is User properties are not private:
public Invitee(User u, int eventDescision) {
super(u.userID, u.firstName, u.lastName, u.mobileNumber, u.dateAccountCreated);
...
You can:
Use decorator design patter in Invitee
Define costructor User(User u)
as people manthioned before: use super() with all parameters
Remember that super is calling constructor of superclass, so you can't call constructor which is not defined.
I am trying to create a constructor that takes a field as a parameter, then puts it in a field that is stored in a superclass. Here is the code I am using
public crisps(String flavour, int quantity) {
this.flavour = super.getFlavour();
this.quantity = quantity;
}
In the superclass I have initialised the field with
private String flavour;
and I have an accessor method
public String getFlavour() {
return flavour;
}
I am getting an error "flavour has private access in the superclass", but I believe this shouldn't matter as I am calling the accessor method that returns it to the field?
What you should do:
Add a constructor to your super class:
public Superclass {
public SuperClass(String flavour) {
// super class constructor
this.flavour = flavour;
}
}
In the Crisps class:
public Crisps(String flavour, int quantity) {
super(flavour); // send flavour to the super class constructor
this.quantity = quantity;
}
Comments
Some comments to your question:
"In the superclass I have initialised the field with "
private String flavour;
This is not an initialization, it is a declaration. An initialization is when you set a value.
"I am getting an error " flavour has private access in the superclass" but I believe this shouldn't matter as I am calling the accessor method that returns it to the field?"
When you call a accessor (aka getter), it is ok - depends on the getter visibility.
The problem in you code is the:
this.flavour =
because flavour is not a field declared on Crisps class, but on the supper class, so you can't do a direct access like that. you should use my suggestion or declare a setter on the super class:
public void setFlavour(String flavour) {
this.flavour = flavour;
}
Then you can use it on the child class:
public Crisps(String flavour, int quantity) {
this.quantity = quantity;
super.setFlavour(flavour);
}
flavour is private. Although you're reading it from the public method, you're assigning it to a private field, and you likely didn't declare it in this class.
You could set flavour to protected in the parent class or define a setter for it
Ultimately your code doesn't really make sense though. Even if it did compile, it would be more or less: flavour = flavour. Perhaps you should rethink what you're trying to do a little bit
I think you may need a tighter grasp on Java and Object Oriented Programming.
http://docs.oracle.com/javase/tutorial/java/concepts/
You should start here.
public crisps(String flavour, int quantity)
{
super(flavour);
this.quantity = quantity;
}
This should work as see Docs
make
private String flavour;
public,otherwise your subclasses won't have access to this String.
Your superclass doesn't know about existence of any subclass. According to Java documentation, "private" makes any variable and method available within that class,where private variable or method was declared, no any class has access to it,even subclasses.
Once you chance your access modifier, you won't get any errors.
Enum constructors must be either private or package default, and protected or public access modifier is not allowed. Why so
Because an enum, by definition, has a fixed set of instances which are declared and constructed in the enum itself. Using the constructor from outside of the enum class itself thus doesn't make sense.
And AFAIK, an enum constructor is always, explicitely or implicitely, private.
From the Java tutorial:
The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself.
It doesn't make sense to be able to create new instances of an enum, so the language prevents you from doing so!
Enum is not meant to be instantiated (by you).
http://docs.oracle.com/javase/tutorial/reflect/special/enumTrouble.html :
Tip: It is a compile-time error to attempt to explicitly instantiate an enum because that would prevent the defined enum
constants from being unique. This restriction is also enforced in
reflective code. Code which attempts to instantiate classes using
their default constructors should invoke Class.isEnum() first to
determine if the class is an enum.
The reason you can't dynamically extend an enum is that the instantiated values are compiled into the bytecode for the Class object:
public T[] getEnumConstants()
Returns the elements of this enum class or null if this Class object does not
represent an enum type.
As a result, any attempt to construct a new instance would not be able to passed onto the actual Class, since Class objects cannot be changed. If you want this behavior, you'll have to simulate it yourself, and give it some kind of unique value to represent each one, then have an ordinal counter, and finally a static map (or some other structure) to hold all the values.
public class MyEnum {
private static AtomicInteger nextOrdinal = new AtomicInteger(0);
private static Map<Integer, MyEnum> instances =
new HashMap<Integer, MyEnum>();
private int ordinal;
private String name;
public MyEnum(String name) {
super();
this.ordinal = nextOrdinal.incrementAndGet();
this.name = name;
instances.put(Integer.valueOf(this.ordinal), this);
}
public String name() {
return name;
}
public int ordinal() {
return ordinal;
}
public static Set<MyEnum> getEnumConstants() {
return Collections.unmodifiableSet(instances.values());
}
public static MyEnum fromInt(int ordinal) {
return instances.get(Integer.valueOf(ordinal));
}
public static MyEnum fromString(String name) {
for (MyEnum val : instances.values()) {
if (val.name().equals(name)) {
return val;
}
}
return null;
}
}
You'll probably also want a .equals and .hashcode method, as well as preventing the same name from being used more than once (which you could do in the constructor and throw an IllegalStateException or something if you have a duplicate name).