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:13

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.

查看更多
【Aperson】
3楼-- · 2020-06-09 08:14

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

查看更多
beautiful°
4楼-- · 2020-06-09 08:16

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.

查看更多
Evening l夕情丶
5楼-- · 2020-06-09 08:18

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.

查看更多
走好不送
6楼-- · 2020-06-09 08:21

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.)

查看更多
Animai°情兽
7楼-- · 2020-06-09 08:22

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.

查看更多
登录 后发表回答