Tila tila
Tila tila

Reputation: 47

How to make a Constructor without parameters?

I have to write a program that has a constructor without parameters. I created another short program as an example to show what I do not understand. So I have a class with the main-method:

public class Dog {
    public static void main(String[] args) {

    CharacteristicsOfTheDog Dog1 = new CharacteristicsOfTheDog(20, 40);
        System.out.println(Dog1.toString());

    }
}

Now implemented another class:

public class CharacteristicsOfTheDog {

    int size = 0;
    int kilogram = 0;


    public CharacteristicsOfTheDog(/*int size, int kilogram*/) {
        // this.size = size;
        // this.kilogram = kilogram;
    }

    public double getSize() {
        return size;
    }

    public double getKilogram() {
        return kilogram;
    }

    public String toString() {
        return "The Dog is " + getSize() + " cm and " + getKilogram() + " kg";

    }
}


In the class "CharacteristicsOfTheDog" in "public CharacteristicsOfTheDog()" I removed the parameters by commenting them out. So the Problem is: if I remove the parameters the program does not work:/ but my task is to do this without the parameters (as far as I understood). Can someone help me please?

Upvotes: 0

Views: 153

Answers (2)

WJS
WJS

Reputation: 40034

Unless CharacteristicsOfTheDog is a subclass or you have a constructor with parameters, you don't need an empty constructor. Just omit it. The following works just fine.

If the parent class has a constructor with arguments, then the parent class will need an explicit empty constructor, but the following should still work.

CharacteristicsOfTheDog cotd = new CharacteristicsOfTheDog();
   cotd.setKilogram(100);
}

class CharacteristicsOfTheDog {
    int size = 0;
    int kilogram = 0;


    public void setSize(int size){
        this.size = size;
    }

    public void setKilogram(int kilogram){
        this.kilogram = kilogram;
    }
}

Depending on your use case, you might want to make the Characteristics class an interface and implement it.

Upvotes: 1

Kevin Hooke
Kevin Hooke

Reputation: 2621

Keep your no-arg constructor and then add setters for your properties:

public class CharacteristicsOfTheDog {

    int size = 0;
    int kilogram = 0;

    public CharacteristicsOfTheDog() {
    }

    public void setSize(int size){
        this.size = size;
    }

    public void setKilogram(int kilogram){
        this.kilogram = kilogram;
    }
}

In your other class, call:

CharacteristicsOfTheDog dog1 = new CharacteristicsOfTheDog();
dog.setSize(20);
dog.setKilogram(40);

As a suggestion, the naming of your class as CharacteristicsOfTheDog is rather literal and stating the obvious. Properties and methods of a class are what describes the characteristics of a class in terms of it's properties and behavior. If you just name your class Dog, that would be perfect. No need to state the obvious.

Upvotes: 2

Related Questions