Search code examples
javaconstructordefault-constructor

Pretty simple constructor question that I just can't get. Java


  • Create a class with a default constructor (one that takes no arguments) that prints a message. In your main() method, create an object of this class.
  • Add an overloaded constructor to your code from step 1. The new constructor should take a String argument and print it along with your message. Modify main() so that it creates a second object of this class, using the new constructor.

So the second part is literally like written in another language to me I have absolutely no idea how to do that, and the first part here's what I got so far:

public class Constructors {
    System.out.println("Message");
    public static void main(String[] args) {
    }
}

It's giving me an error when I'm just trying to print that message. I'm so confused, I'm not asking you to do my lab for me by any means but I'm so confused by this it's out of control.


Solution

  • The constructor shouldn't be the name of your class, the constructor is the method that creates an instance of your class (object)

    So the first point means that you create an object without parameters that will print a message when you call it from the main method

    public class WhateverClass{
    
        //this is the first constructor
        public WhateverClass(){
    
            System.out.prinln("A message");
    
        }
    
        //this is the main method
        public static void main (String[] args){
            new WhateverClass(); //will print the message
        }
    }
    

    Then you create another constructor that gonna overload the first one because it gonna have the same signature except it gonna takes a parameter. And then you call it from main method exactly as the first one. Here:

    public class WhateverClass{
    
        //this is the first constructor
        public WhateverClass(){
    
            System.out.prinln("A message");
    
        }
    
        //this is the second constructor
        public WhateverClass(String message){
    
            System.out.prinln(message);
    
        }
    
        //this is the main method
        public static void main (String[] args){
            new WhateverClass(); //will print the message
            new WhateverClass("A message");
        }
    }
    

    And your exemple doesn't work because your print method is not in any method and cannot be executed from where it is.

    You should really read books and articles about the basics of OO programmation.