Create constructors for the following classes that assign passed values to the p
ID: 3902470 • Letter: C
Question
Create constructors for the following classes that assign passed values to the private data members (remember to verify if input if valid and compatible with data member): Java
1.1.
class Person {
private String name;
private int age;
private String address;
//insert constructor here
}
1.2.
class Taxonomy {
private String class;
private String species; //no need to check if species is valid for given class
private int number_of_legs; //mammals (class) cannot have more than 4 legs
private String continent; //must be a valid continent
//insert constructor here
}
Explanation / Answer
class Person {
private String name;
private int age;
private String address;
Person(String name, int age, String address)
{
// Checking for age
if(age >= 1)
{
name = name;
age = age;
address = address;
}
else
{
System.out.println("Data is invalid. Try again.");
}
}
}
class Taxonomy {
// below line throws an error: <identifier> expected
// because class can't be name of a variable
// So, renamed it to clas
private String clas;
private String species; //no need to check if species is valid for given class
private int number_of_legs; //mammals (class) cannot have more than 4 legs
private String continent; //must be a valid continent
Taxonomy(String clas, String species, int number_of_legs, String continent)
{
// Checking for number_of_legs
// Checking for continents
// If both are proper, assigning values
if(number_of_legs <= 4 && (continent == "Asia" || continent == "Australia" || continent == "Antarctica" || continent == "Europe" || continent == "North America" || continent == "South America"))
{
clas = clas;
species = species;
number_of_legs = number_of_legs;
continent = continent;
}
else
{
System.out.println("Data is invalid. Try again.");
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.