Jump to content

Java - Save constructor input in variable

Go to solution Solved by Butter1484,
public class Tomato extends Vegetable
{
	private String weight;

	public Tomato(String size, String weight)
	{
		this.weight = weight;
		// stuff
	}

	public void information()
	{
		stuff.add(weight)
	}
}

 

Pseudo-code:

public class Tomato extends Vegetable
{
	public Tomato(String size, String weight)
	{
		// stuff
	}

	public void information()
	{
		stuff.add(weight)
	}
}

If that makes any sense, I want to access the "weight" parameter from the constructor to use in another function. How could I do that? I'm new to java.

Link to comment
https://linustechtips.com/topic/548720-java-save-constructor-input-in-variable/
Share on other sites

Link to post
Share on other sites

It would go something like this

public Tomato(String size, String weight)

{

 size = "Small";

 weight = "5 oz.";

}

public String getWeight(){

 return weight;

}

the constructor I gave you is a default constructor. You can also have a constructor which allows custom values. 

Current PC: Origin Millennium- i7 5820K @4.0GHz | GTX 980Ti SLI | X99 Deluxe 

 

Link to post
Share on other sites

2 hours ago, Butter1484 said:

No it shouldn't, it's a constructor

Yeah whoops my bad. Haven't written constructors myself in a while since I use eclipse lol.

 

2 hours ago, MagnesiumPC said:

Ugh... I hate Java.

 

Please stop using that devil language.

 

(The comments above pretty much should solve your problem)

Good for learning. Not so much for real world/professional applications which require efficiency 

Current PC: Origin Millennium- i7 5820K @4.0GHz | GTX 980Ti SLI | X99 Deluxe 

 

Link to post
Share on other sites

Just now, afyeung said:

Good for learning. Not so much for real world/professional applications which require efficiency 

Yeah, it teaches the base components of development, but doesn't do much from there.

 

Rust, Python, and C are my favorite languages right now.

Link to post
Share on other sites

42 minutes ago, MagnesiumPC said:

Ugh... I hate Java.

 

Please stop using that devil language.

 

(The comments above pretty much should solve your problem)

To be honest I just wanted to learn to mod minecraft to learn a bit more about how openGL works, on my own I would only work in C++ or Python

 

By the way, I think you were the person who recommended "The Innovators" to me. I finished it, it was really great. Thanks.

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×