How to test default constructor in a different class in Java - java

How do you test a default constructor in one class and then test it in a different class?
This is the code for the Person class which has the default constructor.
I'm not sure in the PersonTester class how to access this default constructor and how to test it - what I have so far for the second class is also below.
Any help will be muchly appreciated, thanks :)
class Person {
// Data Members
private String name; // The name of this person
private int age; // The age of this person
private char gender; // The gender of this person
// Default constructor
public Person() {
name = "Not Given";
age = 0;
gender = 'U';
}
// Constructs a new Person with passed name, age, and gender parameters.
public Person(String personName, int personAge, char personGender) {
name = personName;
age = personAge;
gender = personGender;
}
// Returns the age of this person.
public int getAge( ) {
return age;
}
// Returns the gender of this person.
public char getGender( ) {
return gender;
}
// Returns the name of this person.
public String getName( ) {
return name;
}
// Sets the age of this person.
public void setAge( int personAge ) {
age = personAge;
}
// Sets the gender of this person.
public void setGender( char personGender ) {
gender = personGender;
}
// Sets the name of this person.
public void setName( String personName ) {
name = personName;
}
} // end class
import java.util.Scanner;
public class PersonTester {
// Main method
public static void main(String[] args){
// TEST THE DEFAULT CONSTRUCTOR FIRSTLY.
// Create an instance of the Person class.
Person person1 = new Person();
Scanner input = new Scanner(System.in);
// Get the values from user for first instance of Person class.
System.out.println("Person 1 Name: ");
person1.setName(input.nextLine());
System.out.println("Person 1 Age: ");
person1.setAge(input.nextInt());
System.out.println("Person 1 Gender: ");
person1.setGender(input.next().charAt(0););
// Alternatively assign values to the Person class.
// person1.setName("Not Given");
// person1.setAge(0);
// person1.setGender("U");
}
}

Your test would look like:
#Test
public void testDefaultConsturctor(){
Person person = new Person();
Assert.assertEquals(person.getName(),"Not Given");
Assert.assertEquals(person.getAge(),0);
Assert.assertEquals(person.getGender(),'U');
}

You can test default constructor in the second class without using asserts with this code
Person defaultPerson = new Person();
System.out.print("My default name is: " + defaultPerson.getName());
System.out.print("My default age is: " + defaultPerson.getAge());
System.out.print("My default gender is: " + defaultPerson.getGender());
By the way, I don´t know what´s the problem, because you are calling default constructor in your second class (PersonTester)

Related

I'm trying to write a code that uses method overload to print out my statement

I have this program that has to ask the user if they want to enter the students name only or to enter the students name and banner ID. Then they can type either "just name" or "both", then the appropriate question will follow. Using the Student class I made, I have to use the appropriate constructor to print out the answer to the screen, either just students name or students name and banner ID. I think I'm getting messed up on how to create the constructors, the instructions say to create three constructors, one that takes the name and banner ID, one that takes just name, and one that takes no arguments and it wants me to create them inside the Student class, I thought they got created inside the main class to access the Student class.
package classwork6_2;
import java.util.Scanner;
public class ClassWork6_2 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Would you like to enter student's name only or name and banner ID?: ");
String response = s.nextLine();
String name;
long banID;
if(response.equalsIgnoreCase("just name")){
System.out.print("Enter student's name: ");
name = s.nextLine();
} else if(response.equalsIgnoreCase("both")){
System.out.print("Enter students name: ");
name = s.nextLine();
System.out.print("Enter student's banner ID: ");
banID = s.nextLong();
}
Student nameBanID = new Student();
nameBanID.setNameBanID(name, banID);
Student n = new Student();
n.setName(name);
System.out.print("Students name is: " + n.getName());
System.out.print("Student's banner ID is: " + n.getNameBanID());
}
}
Student class
package classwork6_2;
public class Student {
private String name;
private String bannerID;
Student nameBanID = new Student();
Student n = new Student();
Student none = new Student();
public String getNameBanID(){
return bannerID + name;
}
public String getName(){
return name;
}
public void setNameBanID(String name, long banID){
bannerID = bannerID + name;
}
public void setName(String name){
this.name = name;
}
}
You're getting a stack overflow error because of these lines in your Student class
Student nameBanID = new Student();
Student n = new Student();
Student none = new Student();
In your ClassWork6_2 when you call Student nameBanID = new Student(); you are creating an instance of the Student class and assigning it to the nameBanID variable. When you are creating an instance of the class it is immediately hitting the line that says Student nameBanID = new Student(); causing your code to go through a loop of creating a new student until a stack overflow error occurs.
Here are how the three constructors should look
private String name;
//changed bannerID to long to match input from code example
private long bannerID;
public Student(String name){
setName(name);
}
public Student(long bannerID){
setBannerID(bannerID);
}
public Student(String name, long bannerID){
setName(name);
setBannerID(bannerID);
}
Your current code does not define any constructors, but java will create a default constructor for you when you do not define one. Once your constructor is defined you can create a student object using those constructors.
String studentName = "Jeffery";
long bannerID = 123456789;
Student studentWithName = new Student(studentName);
Student studentWithBannerID = new Student(bannerID);
Student studentWithNameAndBannerID = new Student(studentName,bannerID);
Here are all of the modifications I made to your student class
class Student {
private String name;
private long bannerID;
public Student(String name){
setName(name);
}
public Student(long bannerID){
setBannerID(bannerID);
}
public Student(String name, long bannerID){
setName(name);
setBannerID(bannerID);
}
public Student(){}
public String getNameBanID(){
return bannerID + name;
}
public String getName(){
return name;
}
public long getBannerID(){
return bannerID;
}
public void setBannerID(long bannerID){
this.bannerID = bannerID;
}
public void setName(String name){
this.name = name;
}
}
When you create a new Student object, you then create and initialize another 3 Student objects. This causes a recursion of Student creation, resulting in a java.lang.StackOverflowError.
You also don't seem to have a constructor for your Student class (eg. public Student () {...}). Ideally, the constructor is where you would initialize your class variables.
Try this: instead of creating the 3 Student objects in the class itself, create them in the main method. Also add in a constructor method for your Student class

How to pass variables between classes?

I am very new to Java and have searched through previously asked questions which haven't helped my issue...
How do I pass the int variable age, and the String name, from the main class to the Person class?
package engineers;
import java.util.Scanner;
public class Engineers {
public static void main(String[] args) {
// TODO code application logic here
Scanner scan = new Scanner(System.in); //declaration and ssignment of scanner
System.out.println("Enter name: "); //name prompt
String name = scan.next(); //reads name input from user
System.out.println("Enter age: "); //age prompt
int age = scan.nextInt(); //reads age input from user
System.out.println("Pay check amount: ");
double salary = scan.nextDouble();
Person person = new Person();
}
private static class Person {
/**
* A default constructor
*/
public Person() {
}
/**
* method for displaying the computation result
*/
double avgSalary = 40000 * Math.sqrt(Math.exp(0.04295 * age + 0.141) );
public void showData(int age, double pay){
System.out.printf( "%s earns $%4.3f for age %3d.\n", name, (pay*Math.sqrt(age)*.15), age);
}//end method showData
}
}
You should use Person constructor like this:
public Person(int age, String name) {
this.age = age;
this.name = name;
}
And add two fields in your Person class, before your constructor:
private int age;
private String name;
Then I am assuming you need to use this variables inside the person class, in order to do this, you can do something like this:
double avgSalary = 40000 * Math.sqrt(Math.exp(0.04295 * this.age + 0.141) );
To reference your variable:
public void showData(){
System.out.printf( "%s earns $%4.3f for age %3d.\n", this.name, (pay*Math.sqrt(this.age)*.15), this.age);
}//end method showData
Finnaly, you need to instantiate your Person object to use it:
Person p = new Person(name, age);
I would also recommend (since you are learning java), to understand the difference between getters/setters and constructor approach: Setter methods or constructors
You mean something like this?
int age;
String name;
class Person(int age, String name) {
this.age = age;
this.name = name;
}
Or (And)
void setAge(int age) {
this.age = age;
}
void setName(String name) {
this.name = name;
}
You would want to define a constructor with any argument another class may need for the most basic functioning.
A Person istance would be initialized with a name and age (even though It would be better to store a birth date and calculate the age against the current date).
To do this, you'd need the class Person to look like this:
public class Person{
private String name;
private Date birthdate;
//Constructor method
public Person(String n, Date bd){
name=n;
birthdate=bd;
}
//Other methods
}
In the main() method, you would then create a new istance of Person, after getting anything needed, like this:
Person p = new(name, date);

Changing public data to private data in Java

I want to change the default constructor (person1) from public to private and then ask the user to input the information instead of the given values.
I have two different classes - Person; which is encapsulated and then PersonTest which tests the information.
class Person {
// Data Members
private String name; // The name of this person
private int age; // The age of this person
private char gender; // The gender of this person
// Default constructor
public Person() {
name = "Not Given";
age = 0;
gender = 'U';
}
// Constructs a new Person with passed name, age, and gender parameters.
public Person(String personName, int personAge, char personGender) {
name = personName;
age = personAge;
gender = personGender;
}
// Returns the age of this person.
public int getAge( ) {
return age;
}
// Returns the gender of this person.
public char getGender( ) {
return gender;
}
// Returns the name of this person.
public String getName( ) {
return name;
}
// Sets the age of this person.
public void setAge( int personAge ) {
age = personAge;
}
// Sets the gender of this person.
public void setGender( char personGender ) {
gender = personGender;
}
// Sets the name of this person.
public void setName( String personName ) {
name = personName;
}
}
import java.util.Scanner;
public class PersonTest {
// Main method
public static void main(String[] args){
// Create first instance of Person class to test the default constructor.
Person person1 = new Person();
// Create a new instance of the Person class.
Person person2 = new Person();
Scanner input = new Scanner(System.in);
// Get the values from user for first instance of Person class.
System.out.println("Person 2 Name: ");
person2.setName(input.nextLine());
System.out.println("Person 2 Age: ");
person2.setAge(input.nextInt());
System.out.println("Person 2 Gender: ");
person2.setGender(input.next().charAt(0));
// Print out the information.
System.out.println("Person 1 Name = " + person1.getName());
System.out.println("Person 1 Age = " + person1.getAge());
System.out.println("Person 1 Gender = " + person1.getGender());
System.out.println("");
System.out.println("Person 2 Name = " + person2.getName());
System.out.println("Person 2 Age = " + person2.getAge());
System.out.println("Person 2 Gender = " + person2.getGender());
System.out.println("");
}
}
One of the main purposes of constructor to be accessible from "outside", so that external classes can instantiate and use your class. You should not make constructor private. It will not be accessible, so main purposes of it will be violated!
If you do not want a default-constructor, simply do not specify one. As soon as you write at least one constructor with paramters, Java does not provide a default-constructor unless you wirte one.
Example:
public class AClass
{
int value = 0;
}
public class BClass
{
int value;
public BClass()
{
value = 0;
}
public BClass(int value)
{
this.value = value;
}
}
This classes have default-constructors and you can write
AClass a = new AClass();
BClass b = new BClass();
to get new instances of this classes.
public class CClass
{
int value;
public CClass(int value)
{
this.value = value;
}
}
This class does not have a default-constructor, since at least one other constructor is specified and no default-constructor is written. Thus
CClass c = new CClass();
will result in a syntax-error.

Setting Variable in Class that Extends other class

the psuedo for what im trying to do is
-send Array of EMPLOYEE objects to Restaurant Class
-In Class RESTAURANT give each of the employee objects a name and last name (last name not in employee Class but in PERSON Class which Employee CLass Extends.
-print say employeeList[1].getLastName()
hopefully my code explains better
class Person {
public Person(final String last) {
}
}
class Employee extends Person {
private String firstName;
// getFirstName method
// getLastName Method
Employee(final String first, final String last) {
super(last);
}
}
class Restaurant { // set first object in array have first and last name
public void setFirstLast(final Employee[] employeeList) {
String firstName = "Jovana";
String lastName = "Valdez";
employeeList[0] = new Employee(firstName, lastName); // set up via constructor
}
}
public class Main {
private String lastName;
public static void main(final String[] args) {
Employee[] employeeList = new Employee[1]; // my array of Employee objects, all set to null
Restaurant restaurant = new Restaurant();
restaurant.setFirstLast(employeeList);
}
}
from main when i try to print System.out.printf("first is %d\n",arrayList.getFirst()); i get null for the value as well as the value for the last name so what is the correct way to go about and set values to objects in the array?
Edit arrayList initialized in Class restaurant by
public Table[] create_table_array(Table table,int number) {
Table[] TableList = new Table[number];
int i = 0;
for(i = 0; i < number; i++) {
TableList[i] = table;
}
return TableList;
Your constructor doesn't save firstName, it should look like:
Employee(String first, String last) {
super(last);
firstName = first;
}
You did not make good constructor of Person class and it class does not have instance variable lastName in which you should assign value you get in constructor as a parameter.
Also constructor of Employee does not assign any value to firstName.
What ArrayList ?As i see you are working with arrays?I didn't see it in code anywhere?
System.out.printf("first is %d\n",**arrayList**.getFirst());so command is wrong.
Any code that has meaning to me and can be compilled is to fix those things and delete formatting options you putted in System.out.printf because you are not formatting numbers.
So code look like :
class Person {
String lastName;
public Person(final String last) {
lastName=last;
}
}
class Employee extends Person {
private String firstName;
public String getFirstName()
{return firstName;}
public String getLastName()
{return lastName;}
Employee(final String first, final String last) {
super(last);
firstName=first;
}
}
class Restaurant { // set first object in array have first and last name
public void setFirstLast(final Employee[] employeeList) {
String firstName = "Jovana";
String lastName = "Valdez";
employeeList[0] = new Employee(firstName, lastName); // set up via constructor
}
}
public class Main {
private String lastName;
public static void main(final String[] args) {
Employee[] employeeList = new Employee[1];
Restaurant restaurant = new Restaurant();
restaurant.setFirstLast(employeeList);
System.out.printf("first is "+employeeList[0].getFirstName()+" "+employeeList[0].getLastName());
}
}

how do is this the correct way of writing this <class name> <object name > = new constructor name?

can some one please help me am having a compilation error with the last part of this code
its saying create constructor please help
public class Officer {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the name of the Soldier: ");
String name = input.nextLine();
System.out.print("Enter the sex of the Soldier: ");
String sex = input.nextLine();
System.out.print("Enter the Age of the Soldier: ");
String age = input.nextLine();
Soldier soldier = new Soldier(name, sex, age);
}
}
package officer;
public class Soldier {
private String soldierName;
private int soldierAge;
private char soldierSex;
public void Soldier( String name, char sex, int age) {
soldierName = name;
soldierSex = sex;
soldierAge = age;
}
public String getSoldierName() {
return soldierName;
}
public char getSoldierSex() {
return soldierSex;
}
public int getSoldierAge() {
return soldierAge;
}
}
The class Soldier needs to define a matching constructor
public Soldier (String name, String sex, String age) {
// do stuff
}
This is the method that what be executed, when you call new Soldier(name, sex, age)
It ok, except:
sex should be en enum type
age should be an integer (or float) type
you should validate user input
An SEX enum:
public enum SEX {
MALE, FEMALE
}
A constructor:
public Soldier (String name, SEX sex, int age) {
}
You would need something like:
public class Soldier {
public Soldier(String name, String sex, int age) {
}
}
edit: with the new info provided you should delete the void in the public void Soldier since void would mean public void Soldier is a method of class Soldier while it's supposed to be the constructor.

Categories

Resources