Click here to Skip to main content
15,893,487 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
1. Create a class Tree that contains the following:
• 2 private instance variables corresponding to name (e.g. birch, oak, walnut, etc.) and age (e.g. 123, 16, 223, etc.).
• A constructor that allows the 2 instance variables to be initialised to custom values. If a negative value is passed for age, it should print a message that it does not allow negative values (or similar), otherwise, it should allow all instance variables to be initialised.
• 2 set methods that allow each of the instance variables to be modified to a custom value. In the case of the age setter, if a negative value is passed, it should print a message that it does not allow negative values (or similar), otherwise, it should allow that variable to be changed.
• 2 get methods that allow you to access each of the instance variables.
• A method called printDetails that prints the values of the 2 instance variables.

What I have tried:

Java
public class Tree{
	private String name;
	private int age;

	public Tree(){
			treeName = "a type of tree";
			age = "age of tree";
	}

	public Tree(String treeName, int age,){
			treeName = aName;
			age = age;

	}
Posted
Updated 11-Apr-18 1:33am

1 solution

What I've you tried is wrong.
Quote:
public Tree(){
treeName = "a type of tree";
age = "age of tree";
}
Should be
Java
public Tree(){
			name = "a type of tree";
			age = 0; // or whatever (positive) int value
	}



Quote:
public Tree(String treeName, int age,){
treeName = aName;
age = age;

}

should be something like:
Java
public Tree(String name, int age )
{
  this.name = name;
  setAge(age);
}
With
Java
public void setAge(int age)
{
  if (age >= 0)
  {
    this.age = age;
  }
  else
  {
    System.out.println("age must be greater than (or equal to) 0");
  }
}


I suppose you're now able to complete the task.
 
Share this answer
 
Comments
Maciej Los 11-Apr-18 11:15am    
5ed!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900