Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Dear expert, I'm learning java constructor and have the following question: What is the difference for the constructor which takes initialname as parameter, and the

Dear expert,

I'm learning java constructor and have the following question:

What is the difference for the constructor which takes initialname as parameter, and the method takes new name with parameter ?

the two methods I refer to are these :

public Pet2(String initialName, int initialAge,double initialWeight)

public void setPet(String newName, int newAge, double newWeight)?

Why do I need to do the things to times ?

Thank you.

public class Pet2

{

private String name;

private int age; //in years

private double weight;//in pounds

public Pet2(String initialName, int initialAge,

double initialWeight)

{

set(initialName, initialAge, initialWeight);

}

public Pet2(String initialName)

{

set(initialName, 0, 0);

}

public Pet2(int initialAge)

{

set("No name yet.", initialAge, 0);

}

public Pet2(double initialWeight)

{

set("No name yet.", 0, initialWeight);

}

public Pet2( )

{

set("No name yet.", 0, 0);

}

public void setPet(String newName, int newAge, double newWeight)

{

set(newName, newAge, newWeight);

}

public void setName(String newName)

{

set(newName, age, weight);//age and weight are unchanged.

}

public void setAge(int newAge)

{

set(name, newAge, weight);//name and weight are unchanged.

}

public void setWeight(double newWeight)

{

set(name, age, newWeight);//name and age are unchanged.

}

private void set(String newName, int newAge, double newWeight)

{

name = newName;

if ((newAge < 0) || (newWeight < 0))

{

System.out.println("Error: Negative age or weight.");

System.exit(0);

}

else

{

age = newAge;

weight = newWeight;

}

}

public String getName( )

{

return name;

}

public int getAge( )

{

return age;

}

public double getWeight( )

{

return weight;

}

public void writeOutput( )

{

System.out.println("Name: " + name);

System.out.println("Age: " + age + " years");

System.out.println("Weight: " + weight + " pounds");

}

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Online Systems For Physicians And Medical Professionals How To Use And Access Databases

Authors: Harley Bjelland

1st Edition

1878487442, 9781878487445

Students also viewed these Databases questions

Question

How is liquidity a source of risk?

Answered: 1 week ago

Question

What is human nature?

Answered: 1 week ago