Steven Zhao
Steven Zhao

Reputation: 301

Difference between constructors and methods

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); 
    }
}

Upvotes: 12

Views: 13442

Answers (14)

sig_seg_v
sig_seg_v

Reputation: 570

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.

Upvotes: 2

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48600

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.

Upvotes: 5

Dici
Dici

Reputation: 25950

You did not get the basic concept of an instance, which is fundamental in OOP. If you want a metaphor, let's talk about cars.

I'm pretty sure you know what a car is; you know that it enables you to move from one place to another, that it has 4 wheels and so on. It is a concept, and the actual car you have in your garage is an instance of this concept (<=> class).

A constructor's goal is to create an instance, not to print some text. Without a constructor, you will never be able to call a non-static method of your class. You won't be able to drive the concept of a car, you will need to build a car first.

Just review those notions; you will get nowhere without it.

Upvotes: 21

JacksOnF1re
JacksOnF1re

Reputation: 3512

I would really rather read a book about the concepts of OOP and in this case java, than reading all the (good) answers here. You will probably get a lot of answers, since this question is fairly popular, but the answers won't go into all the necessary detail.

But one thing I want to mention in short:

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;
}

A method can return with some sort of answer. So what does this method do? It returns the value, saved in the variable with the name puppyAge, which is an integer. So if you call the method myPuppy.getAge(), everything in this method (indeed the print out, too), will be processed and afterwards it returns. In your case you don't save the return value anywhere. But the 'normal' thing you want to do would be to access the age of the puppy via the method and actually DO something with it, like calculate the average age of all your puppys and stuff. Sure, you can access the variable here from outside of the class, because you did not set the visibility modifier, like public, private, protected.

public class Puppy {
    int puppyAge;

Actually no public modifier has also a meaning, but this is not relevant for now. So what you want to do is to set it for example to private:

private int age;

and access it via a method like getAge() and do something with it like:

int allAgesummed = puppy1.getAge() + puppy2.getAge() +
puppy3.getAge();

Lastly, if you just want to print out the age on the console, your method should only do exactly that one thing and should be named accordingly, like:

public void printAgeToConsole(){
    System.out.println("Age: " + age);
}

void indicates that this method does something, but doesn't return anything.

Upvotes: 2

felipeek
felipeek

Reputation: 1213

I guess your question is why the constructor is created using...

public Puppy(String name)

...instead of...

public static void Puppy(String name)

..., right?

If it is, firstly you should now that a constructor is a special method owned by a class that is called whenever you create a new instance of that class. So if, for example, you have this class...

public class Clazz {
    public Clazz (String s) {
         System.out.println(s);
    }
}

..., then whenever you create a new instance of this class like...

Clazz c = new Clazz("Hello World");

..., the constructor will be called and that method will be executed. (In this example, it would print "Hello World" on the screen.)

That said, you can see that the constructor is a method, but it's a special method called when the class is instantiated. So, regarding your question, the reason why the constructor is right this way instead of a regular method header is to indicate to the compiler that it is a constructor and not a regular method. If you write public void Clazz () instead of public Clazz (), then the compiler will not recognize your constructor, and will think it's just a regular method.

Note that constructors never return anything, so it would not be necessary to use the void keyword. Also, there's no sense in making a constructor static, since the constructor is called when a new object is instantiated.

Upvotes: 10

Dog
Dog

Reputation: 29

constructor is public Class(){ define the variable that need to be use in whole class method is go under constructor public void methodName(){} u may change void to variable type that u want the method return the specific type.

Upvotes: 2

Qyriad
Qyriad

Reputation: 169

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.

Upvotes: 2

Ryan Sayles
Ryan Sayles

Reputation: 3431

A Constructor does just that, it "constructs" the object that you are creating it technically is a specific type of Method. A Method is used to modify the object, mostly to do a single piece of logic. See: single responsibility principle.

Classes/methods should be simple and handle exact pieces of information for example take a Shape object, if you wanted it's attributes to be length, width, height, volume, area, ect... your constructor would have to be:

public Shape (double length, double width, double height, double volume, double area, ect...) {
    //code here
} 

(notice the name of this method should be the same as the name of the class, signifying a 'Constructor`)

this is what is know as a code smell, specifically: too many parameters. It is difficult to read, not very organized and just a bad way to write code. So instead, methods are used to set these variables:

public void setLength(double length) {
    //code here
} 

Then your constructor would only be:

public Shape() {
    //code here
}

This is just one, simple example. In many cases you may want to pass a parameter (or a few) into the constructor depending on the case.

Upvotes: 2

Auberon
Auberon

Reputation: 715

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");

Upvotes: 2

BrianT.
BrianT.

Reputation: 404

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.

Upvotes: 3

Hessam
Hessam

Reputation: 1415

There is a very big difference between constructors and methods. When you instantiate an object like it's done in the program

Puppy myPuppy = new Puppy( "tommy" );

with the use of new keyword the JVM calls the constructor to make the object. So constructors make objects that doesn't exist but methods are associated with objects that exist. You can read more at this link http://www.javaworld.com/article/2076204/core-java/understanding-constructors.html

Upvotes: 3

markspace
markspace

Reputation: 11020

For that example, you don't need a constructor. It's a pretty bad example. A method would work just as well.

(All Java classes have a default constructor if you don't add one, so you could still call new Puppy() to get a instance.)

Upvotes: 2

Spaceman Spiff
Spaceman Spiff

Reputation: 934

A constructor is supposed to be for setting up the object where as a method simply does some action with the object. Java is object oriented so the whole language revolves around the object. Constructors also can not return anything and must be used with new to return an instance of the object created where as methods can return anything or nothing at all.

Upvotes: 2

turingcomplete
turingcomplete

Reputation: 2188

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.

Upvotes: 5

Related Questions