-1

I'm a java self-learner and got stumped with one question about constructor. I got some hints that there's a problem in public void Circle(), but I still don't know how to debug this.. Can someone please help me? Thanks in advance :)

public class Circle {
    public Color color;

    public static void main(String[] args) {
        Circle circle = new Circle();
        circle.color.setDescription("Red");
        System.out.println(circle.color.getDescription());
    } 

    public void Circle() {
        Color color = new Color();
    }

    public class Color {
        String description;

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }
    }
}
GBlodgett
  • 12,704
  • 4
  • 31
  • 45
James
  • 5
  • 3
  • Probably that it's creating a local variable that is shadowing the `color` variable. Also it has `void` in the method signature, so it isnt a constructor – GBlodgett Dec 29 '18 at 04:00
  • Also related: https://stackoverflow.com/questions/6801500/why-do-constructors-in-java-not-have-a-return-type – GBlodgett Dec 29 '18 at 04:11

3 Answers3

3

That is not a constructor. A constructor is not a void method. Also, you have a local color variable in your method. I think you wanted

public Circle() {
    this.color = new Color();
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created.

In your case, you are calling public void Circle()

Note that the constructor name must match the class name, and it cannot have a return type (like void).

Also note that the constructor is called when the object is created.

All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you. However, then you are not able to set initial values for object attributes.

So in your case the constructor should be similar to :

public Circle() {
    //what ever you want here
}
Vishwa Ratna
  • 5,567
  • 5
  • 33
  • 55
0
public Circle() {
    this.color = new Color();
}

constructor don’t have a return type

kbrx93
  • 21
  • 2