开发者

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开发者_StackOverflow中文版 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.


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.


A method invocation should either be part of a method body or an initializer expression or block. Move that println invocation to an actual constructor (google that) and you should be good to go. You can go through the "Starting Java (my sticky thread)" thread aimed to beginners (feel free to offer suggestions).

BTW, there is a difference between default and no-arg constructor. A default constructor is always a no-arg constructor and is automatically provided in case you don't but the reverse is not true.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜