Getters, Setters, Constructors and their parameters - java

Ye've been very helpful so far even though I havn't been great at wording my questions. I think I almost know what I'm doing but I'm trying to get my head around the relationship between getters, setters and constructors. I have two classes as follows
Student and Name and I'm confused about the relationship between the parameters in the getters and setters and constructor
If I remove the parameters from the Name constructor, i.e. this
public Name (){
this.firstName = firstName;
this.lastName = lastName;
and aslo edited the Student constructor to reflect this
public Student(int id, String firstName, String lastName, String street, String area, String city, String country, int age, char gender, String college, String course, int level, int gradePointAverage){ //This is the list of variables called from the Student class
this.id = id;
this.name = new Name(); //I have removed the parameters here
this.name.setFirstName(firstName);
this.name.setLastName(lastName);
this.address = new Address(street, area, city, country);
this.age = age;
this.gender = gender;
this.college = college;
this.course = course;
this.level = level;
this.gradePointAverage = gradePointAverage;
}
I'm not sure what impact it would have. I would be very greatful of someone could explain to me where I should/shouldn't have parameters and why? Understand this concept is what is holding me back from moving any further with coding at the moment.
public class Student {
private Name name; // This is calling from the Name class, giving it the name 'name'
private Address address; // This calls from Address, giving it the name 'address'
private char gender;
private String course, college;
private int gradePointAverage, id, age, level;
public Student(int id, String firstName, String lastName, String street, String area, String city, String country, int age, char gender, String college, String course, int level, int gradePointAverage){ //This is the list of variables called from the Student class
this.id = id;
this.name = new Name(firstName, lastName);
//this.name = new Name();
this.name.setFirstName(firstName);
this.name.setLastName(lastName);
this.address = new Address(street, area, city, country);
this.age = age;
this.gender = gender;
this.college = college;
this.course = course;
this.level = level;
this.gradePointAverage = gradePointAverage;
}
public int getId(){
return id;
}
public String getName(){
return name.toString();
}
public String getAddress(){
return address.toString();
}
public int getAge(){
return age;
}
public char getGender(){
return gender;
}
public String getCollege(){
return college;
}
public int getLevel() {
return level;
}
public String getCourse() {
return course;
}
public int getGradePointAverage() {
return gradePointAverage;
}
public void printStudent() {
System.out.println("The Student " + name.toString() + " is logged under the student ID number " + id + ".");
System.out.println("They live at " + address.toString() + " and their age is " + age + ".");
System.out.println("Their gender is " + gender + ".");
System.out.println("The student studies at " + college + " attending classes in " + course + ".");
System.out.println("Their level is " + level + " and the student grade average in points is " + gradePointAverage + ".");
System.out.println();
}
}
and Name
public class Name{
private String firstName, lastName;
public Name (String firstName, String lastName){
//public Name (){
this.firstName = firstName;
this.lastName = lastName;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
//public String getFirstName() {
// return firstName;
//}
//public String getLastName() {
// return lastName;
//}
///** Returns first name concatenated to last name */
//public String toString() {
// return firstName + " " + lastName;
//}
}

The constructors are for initialization of an instance of an Object to ensure that all the minimum amount of data required for a valid object state are provided at creation time.
In your case Name should have a constructor that requires firstName and lastName because those things are what make the Name object fully initialized. This Object should work just like your Address object you have shown as well.
Otherwise if you use setXXX methods, the Name object is incomplete with the two String objects initialized to null or some other undefined state.

Related

Creating Address Attribute in Java

package week3;
import java.util.ArrayList;
public abstract class TaxPayer {
private final String TFN;
private String firstName;
private String lastName;
private double income;
private Address address(int streetNumber, String streetName, String suburb,
String city, String state, int postcode);
public TaxPayer(String TFN, String firstName, String lastName, double income,
Address address) {
this.TFN = TFN;
this.firstName = firstName;
this.lastName = lastName;
this.income = income;
this.address = address;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public double getIncome() {
return income;
}
public Address getAddress() {
return address;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setIncome(double income) {
this.income = income;
}
public void setAddress(Address i) {
}
public String getFullName() {
return getFirstName() + " " + getLastName();
}
#Override
public String toString() {
return TFN + " " + firstName + " " + lastName + " "
+ income;
}
public static double calcTax(double income) {
return 1;
}
public double calcTax() {
return 1;
}
public static void printArrayListToConsole(ArrayList<TaxPayer> Array) {
for (TaxPayer d : Array) {
System.out.println(d);
}
}
}
package week3;
public class Address {
int streetNumber;
String streetName;
String suburb;
String city;
String state;
int postcode;
public Address(int streetNumber, String streetName, String suburb,
String city, String state, int postcode) {
this.streetNumber = streetNumber;
this.streetName = streetName;
this.suburb = suburb;
this.city = city;
this.state = state;
this.postcode = postcode;
}
#Override
public String toString() {
return streetNumber + " " + streetName + " " + suburb + " " + city + " "
+ state + " " + postcode;
}
}
So, my problem is in creating the address attribute, which must be private. I think I've made the other class correctly yet it still isn't working. As well as this, the attribute isn't working with the fields I try to put in it (streetNumber, streetName, etc), it's coming up with the error 'missing method body, or declare abstract' but I'm unsure why. Any help is appreciated!
private Address address(int streetNumber, String streetName, String suburb,
String city, String state, int postcode);// this is a method not a attribute
Make private attribute of Address Class.
public abstract class TaxPayer {
.
.
.
private Address address; // this is attribute.
.
.
.
//One way is passing the all address attributes in constructor
public TaxPayer(String TFN, String firstName, String lastName, double income,int streetNumber, String streetName, String suburb,
String city, String state, int postcode) {
this.TFN = TFN;
this.firstName = firstName;
this.lastName = lastName;
this.income = income;
this.address = new Address(streetNumber, streetName, String suburb,city, state, postcode);
}
}
second option is use same constructor and make a Address objectin main class and pass into that constructor like :
public TaxPayer(String TFN, String firstName, String lastName, double income,Address address) {
this.TFN = TFN;
this.firstName = firstName;
this.lastName = lastName;
this.income = income;
this.address = address;
}
And while creating Tax Payer Object first create Address Object and pass it.
Address address= new Address(streetNumber, streetName, String suburb,city, state, postcode);
TaxPayer tp= new TaxPayer(TFN, firstName, lastName, income,address);
private Address address(int streetNumber, String streetName, String suburb,
String city, String state, int postcode);
You have to declaring a variable of Address type but this is not the way to declare a variable.
Replace the above code of TaxPayer class with just this
private Address address;

Creating a method where two objects are considered equal if the first and last names are the same.

So within this class, I need to create a Equals method that will check to determine if the two objects have the same name. I tried creating the two objects within the class and just initialize it with "" for the constructor, but it gave an error on the created objects
Person.Java
public class Person
{
String firstName = "";
String lastName = "";
String age = "";
public Person (String firstName, String lastName, String age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public String getAge(){
return age;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public void setAge(String age){
this.age = age;
}
public String toString(){
return firstName + " " + lastName + ", " + age + " years old";
}
}
Here is my driver, so basically I need a method that sees both have the same name and prints out a message saying that they have the same name. My lab states it has to be in the class NOT the driver, which is why I'm lost considering I could easily make an if/else statement within the driver.
public class PersonDriver
{
public static void main(String[] args)
{
Person p1 = new Person("John","Doe", "42");
Person p2 = new Person("John","Doe", "43");
System.out.println(p1);
System.out.println(p2);
}
}

How Can I Input A Custom Class Value Via Scanner?

I am trying to put together a small test application that takes inputs via scanner and puts them in-memory via hashmap and tree set.
Later on I'll search, edit, and delete them (So basically a CRUD), it requires 2 classes an employee class and a company one. I'm trying to take the input for the employee with all the information for the employee including the company which is a foreign custom class object in the POJO.
It won't let me class cast it, what should I do?
Here is the POJO
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
private String ssn;
private Integer salary;
private String birthDate;
private String jobTitle;
#ManyToOne
private Company companyName;
public Employee (String fN, String lN, String SSN, Integer sal, String birth, String jobT, Company compName) {
lastName = lN;
firstName = fN;
SSN = ssn;
sal = salary;
birth = birthDate;
jobT = jobTitle;
compName = companyName;
}
public String toString()
{
return "Employee[Last Name= " + lastName + ", First Name= " + firstName + " SSN= " + ssn + ","
+ "Salary= " + salary + ", Birth Date= " + birthDate + ", Job Title= " + jobTitle + ",]" ;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getSsn() {
return ssn;
}
public void setSsn(String ssn) {
this.ssn = ssn;
}
public Integer getSalary() {
return salary;
}
public void setSalary(Integer salary) {
this.salary = salary;
}
public String getBirthDate() {
return birthDate;
}
public void setBirthDate(String birthDate) {
this.birthDate = birthDate;
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public Company getCompanyName() {
return companyName;
}
public void setCompanyName(Company companyName) {
this.companyName = companyName;
}
}
Here is part of the class the scanner is in
System.out.println("Enter Company Name : ");
String val7 = input1.nextLine();
...
Employee newEmp = new Employee(str1,str2, str3, val4, str5, str6, val7);
If I pass the str7 in, it obviously creates an error as the method takes the CompanyName.
Any idea what I need to be doing as ClassCast doesn't work here.
EDIT here is the company class
public class Company {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
String companyName;
private String description;
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
you need to create instance of Company, don't pass it as string:
System.out.println("Enter Company Name : ");
String val7 = input1.nextLine();
Company company = new Company();
company.setCompanyName(val7);
and use company instead of val7 when you create Employee
Employee newEmp = new Employee(str1,str2, str3, val4, str5, str6, company);
ALSO you have a logical error in the constructor, this
compName = companyName;
should be the other way around ... like this
companyName = compName;
because you want to assign the value from param to the member,
There is only the way you already half took:
you use the scanner and ask for the values that you need to create a new instance of that class
you validate all those values
you use them to create the object
Like:
while (something) {
String newFirstName = scanner.next();
...
int newSalary = scanner.nextInt();
...
Employee newGuy = new Employee(newFirstName, ...
In other words: Scanner only knows how to provide those specific "built-in" types such as String, int, float, ...
Thus: if you need an aggregate of such types, you have collect them "manually".
In your case: simply ask for companies first. Meaning: have the user first enter the companies; and your code create company objects. You could put those into a Map<String, Company> for example. Now, when entering employees, you ask for the company name last; and then your code retrieves the Company object for the name entered.

Creating a class with different argument lengths

How do I create a class that has different lengths of arguments?
public static void main(String[] args) {
group g1 = new group("Redskins");
group g2 = new group("Zack", "Mills", 21);
group g3 = new group("John","Smith",20);
group g4 = new group("Fred","Fonsi",44);
group g5 = new group("Jeb","Bush",26);
System.out.println(g1.getName());
}
}
I want to be able to display the team name (redskins) and then each member after that using one method.
I've tried using two methods and got that to work, but can't get one.
I was thinking about possibly using an array but not sure if that would work.
Thanks for any help.
I have three classes the main, student, and group.
I need the group class to display the group name and then figure out how to display the students information underneath. The only thing, is that my assignment is vague about whether I can use two methods or one.
public class student {
String firstName;
String lastName;
int age;
student(String informedFirstName, String informedLastName, int informedAge){
firstName = informedFirstName;
lastName = informedLastName;
age = informedAge;
}
String getName()
{
return "Name = " + firstName + " " + lastName + ", " + "Age = " + age;
}
}
public class Team{
String name;
Set<Player> players;
public Team(String name){
this.name = name;
}
public void addPlayer(Player p){
players.add(p);
}
}
public class Player{
String name;
etc
}
EDIT for revised question:
Ok, Im going to show a lot here. Heres what a proper Java versio of what you want for student.
public class Student {
private String firstName;
private String lastName;
private int age;
public Student(String firstName, String lastName, int age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
/*
* Use:
* Student s = new Student(Bill, Nye, 57);
* System.out.println(s.toString());
*/
#Override
public String toString() {
return "First Name: " + firstName + ", Last Name: " + lastName + ", Age: " + age;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
The Things to take away from this.
1) Capitalize the first letter of class names! (Student)
2) note the class variables are private (look here for a tutorial Java Class Accessibility) and have getters and setter to control access outside the class.
3) I dont say "getName()" and return name and age. This doesnt make sense. Instead i make it so when you go toString() it shows all the relevant information.
4) Java is an object oriented language which means the classes that model data are supposed (to some extent) model appropriately to the way they are used in real life. This makes it more intuitive to people reading your code.
5) if your Group class (note the capital!) needs to contain many Students use a LIST such as an ArrayList. Arrays would make no sense because you dont know how many Students are going to be in each Group. A SET like i used above is similar to a list but only allows ONE of each item. For simplicity use a list though
6) the THIS operator refers to class (object) variables. In the constructor this.firstName refers to the firstName within the Class (object...an instance of the class) whereas just firstName would refer to the variable in the contructor and not alter the class variable.
use the constructor for that
class group {
String fname,lname;
group(String fname ){
this.fname=fname;
}
group(String fname,String lname){
this.fname=fname;
this.lname=lname;
}
group(String fname,String lname,int age){
this.fname=fname;
this.lname=lname;
this.age=age;
}
public String getName(){
return fname+lname+age;
}
}

Adding in String and int to parent class with super.toString

Okay, so I have 4 different classes for my program, and I'm trying to add a new variable in one of my subclasses. I will show the code for all of the classes involved and then explain what exactly is wrong.
First Code is my Person Class:
class Person {
private String myName; // name of the person
private int myAge; // person's age
private String myGender; // 'M' for male, 'F' for female
// constructor
public Person(String name, int age, String gender) {
myName = name;
myAge = age;
myGender = gender;
}
public String getName() {
return myName;
}
public int getAge() {
return myAge;
}
public String getGender() {
return myGender;
}
public void setName(String name) {
myName = name;
}
public void setAge(int age) {
myAge = age;
}
public void setGender(String gender) {
myGender = gender;
}
public String toString() {
return myName + ", age: " + myAge + ", gender: " + myGender;
}
}
my next class is my Teacher Class:
public class Teacher extends Person {
private static int salary;
private static String subject;
public Teacher(String name, int age, String gender, String subject, int salary) {
super(name, age, gender);
//Constructor
salary = salary;
subject = subject;
public String toString(){
return super.toString() +", Subject: " + subject + " Salary: " + salary;
}
}
}
So the problem with my program is, I'm trying to add in the String Subject and the Int Salary. I'm getting an error that keeps saying "Syntax error on token "String", # expected"(Line 12 of the Teacher Class) and then another one right next to it saying:""Syntax error, insert "EnumBody" to complete BlockStatement"(line 12 of the Teacher Class).
So all I am trying to do is add the new values into my parent class so that when I go to add in a user I can enter their salary and subject and so on. Sorry if i'm not too clear. It might be in plain sight for some of you, if i'm not clear enough please let me know.
Any help is greatly appreciated!
Thanks,
Sully
I haven't looked all through your code, but I believe this is the problem:
public Teacher(String name, int age, String gender, String subject, int salary) {
super(name, age, gender);
//Constructor
salary = salary;
subject = subject;
public String toString(){
return super.toString() +", Subject: " + subject + " Salary: " + salary;
}
You've started overriding toString in the middle of the constructor. You need to close the constructor, then start the toString method:
public Teacher(String name, int age, String gender, String subject, int salary) {
super(name, age, gender);
//Constructor
salary = salary;
subject = subject;
}
public String toString() {
return super.toString() + ", Subject: " + subject + " Salary: " + salary;
}
Ideally, use the #Override annotation to tell the compiler to validate that you really are overriding a superclass method, too:
#Override
public String toString() {
return super.toString() + ", Subject: " + subject + " Salary: " + salary;
}
One issue is:
public Teacher(String name, int age, String gender, String subject, int salary) {
super(name, age, gender);
//Constructor
salary = salary;
subject = subject;
public String toString(){
return super.toString() +", Subject: " + subject + " Salary: " + salary;
}
}
Your toString() method is inside constructor. Move it to outside the constructor.
public Teacher(String name, int age, String gender, String subject, int salary) {
super(name, age, gender);
//Constructor
salary = salary;
subject = subject;
}
public String toString(){
return super.toString() +", Subject: " + subject + " Salary: " + salary;
}

Categories

Resources