Difference between constructors and methods

2020-06-09 07:56发布

Bellow is an example I found on Tutorials Points, an example of a constructor. I got most of them, but I just don't get why you need a constructor and a method.

public Puppy(String name){
    System.out.println("Passed Name is :" + name ); 
}

My question is, what stops you from doing this instead?

public static void Puppy(String name){
    System.out.println("Passed Name is: "+name);
}

Doesn't these two do the same thing once called?

Here is the full program for reference:

public class Puppy {
    int puppyAge;

    public Puppy(String name) {
        System.out.println("Passed Name is :" + name); 
    }

    public void setAge(int age) {
        puppyAge = age;
    }

    public int getAge() {
        System.out.println("Puppy's age is :" + puppyAge); 
        //what does this return do? since the puppyAge is already printed above.
        return puppyAge;
    }

    public static void main(String []args){
        Puppy myPuppy = new Puppy("tommy");

        myPuppy.setAge(2);
        myPuppy.getAge();

        System.out.println("Variable Value :" + myPuppy.puppyAge); 
    }
}

14条回答
唯我独甜
2楼-- · 2020-06-09 08:01

Constructors ARE methods, they are special types of methods, however. Constructors are methods that don't have a return type and must be named after their enclosing class. So why do we need constructors? well, that's how we can create instances of classes. When you want to create an instance of a certain class, you do so by calling its constructor. The constructor reserves memory for the object and returns a reference to the newly created object.

查看更多
Ridiculous、
3楼-- · 2020-06-09 08:02

When you create a new instance of an object (Puppy doggy = new Puppy("Bobby");) the Constructor is immediately called. It constructs the new objects. It constructs it with the name "Bobby". (The Puppy is born with the name "Bobby"). Let's say our puppy is unsatisfied with its name and you want to change it to "Snoopy". Then you would call the method: doggy.setName("Snoopy");

查看更多
Luminary・发光体
4楼-- · 2020-06-09 08:06

Stated in the Java Spec for Constructors:

  • Constructors do not return anything, thus they have no return type.

    In all other respects, the constructor declaration looks just like a method declaration that has no result (§8.4.5).

  • You cannot override a constructor.

    Constructor declarations are not members. They are never inherited and therefore are not subject to hiding or overriding.

  • They cannot access instance variables directly, instead they must use this and super to delegate to the classes' variables.

    An explicit constructor invocation statement in a constructor body may not refer to any instance variables or instance methods or inner classes declared in this class or any superclass, or use this or super in any expression; otherwise, a compile-time error occurs.

查看更多
狗以群分
5楼-- · 2020-06-09 08:07

several good answers about constructors already.

A minor point; you cannot have a static method with the same name as your class. That name is reserved for constructors.

查看更多
一纸荒年 Trace。
6楼-- · 2020-06-09 08:10

A constructor is a type of method. Specifically it is called when you instantiate an object of that class. So in your example if you write:

Puppy pup = new Puppy("Rover");

You make an object called pup and instantiating that object, which allows you to use it. By instantiating it, you call the constructor specified, in this case: public Puppy(String name) which sets prints to "Rover", however this isn't really a good use of a constructor. What would make more sense would be to have String puppyName; as a field variable, and have this.puppyName = name to set p.puppyName equal to what is passed in the constructor.

查看更多
手持菜刀,她持情操
7楼-- · 2020-06-09 08:12

Your first example is a public constructor that is called when you actually create a Puppy. Usually, the constructor would save the name instead of displaying it and throwing it away, so you could refer back to it later, for example:

public class Puppy{
    private String puppyName;

    public Puppy(String name){
        puppyName = name;
    }
    public void bark(){
        System.out.println(puppyName + ": woof!");
    }
    ...
}
...
public static void main(){
    Puppy Spot = new Puppy("Spot"); // here, the constructor is called, which saves the name
                                    // "Spot" into the variable Spot.puppyName.

    Puppy Fido = new Puppy("Fido"); // on this line, the constructor is called again, but this time, the string
                                    // "Fido" is saved into Fido.puppyName.

    Spot.bark();                    // output: "Spot: woof!"
}

I think of a constructor as a method that "returns" a Puppy object, which is why it doesn't have a return type. Methods and variables that are declared static, unlike the puppy's name, do not "belong" to any object in particular, but are shared among all members of the class.

public class Puppy{
    ...
    private static String latinName;
    public static void setLatinName(String newLatinName){
        latinName = newLatinName;
    }
    public static void printLatinName(){
        System.out.println("I am a " + latinName + ".");
    }
};
...
static void main(){
    Puppy Spot("Spot");
    Puppy Fido("Spot");
    Spot.setLatinName("Canis Lupus");
    Fido.setLatinName("Canis Lupus Familiaris");

    Spot.printLatinName();    // output: "I am a Canus Lupus Familiaris."
    // even though we used the Fido object to change the latinName string,
    // the output of Spot's non-static method still reflects the change because
    // latinName is a static field: there is only one String latinName 
    // shared among all members of the class.
}

While you can use a Puppy object to call static methods (which could be especially useful if the Puppy were a polymorphic Canine), the inverse is not also true!

public class Puppy{
    ...
    public static void bark(){
        System.out.println( puppyName + ": woof!"); // this will not compile!
    }
}

It is invalid (and doesn't make sense) to reference non-static data members in the context of a static function! A static function is similar to a static variable: there is only one copy of the function shared among all member objects. This means that you can call Puppy.setLatinName() (instead of Spot.setLatinName()). You do not need to use a specific Puppy object to call a static function: a static function is guaranteed not to depend on any non-static member variables (because it doesn't have any). Calling Puppy.bark() doesn't make sense because the class "Puppy" does not have a puppyName; each individual Puppy has its own puppyName.

I hope this helps. Object oriented programming is very powerful and it's important to understand the basics well! Good luck.

查看更多
登录 后发表回答