Creating a class with different argument lengths - java

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;
}
}

Related

Use of private data variables in simple POJO [duplicate]

This question already has answers here:
Why use getters and setters/accessors?
(37 answers)
Closed 1 year ago.
Recently I was going through the concept of Encapsulation in Java. I was wondering if making data variables private along with public setter methods really make sense in simple POJO class? Please refer below POJO:
public class Employee{
private String id;
private String name;
private String department;
private int age;
public Employee(){
}
public Employee(String id, String name, String department, int age){
this.id = id;
this.name = name;
this.department = department;
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
I mean why am I making the name variable private when I can anyway change it using the setter method?
In the general case, it'll be the very basic
public void setName(String name) {
this.name = name;
}
Where it's identical to just doing employee.name = "william hammond". But imagine a case where you'd like to do implement something like a private String normalize(string username) method where you maybe make it all lower case, check for a valid name or prevent unicode entries. If you make name public initially you'll have users doing employee.name = "whatever they want :) 123" and you'll lose the ability to enforce that constraint.
Also see Why use getters and setters/accessors?
Using getters/setters is just considered good practice, but it can often be overkill - like in your example.
If you have methods that mutate the variable before setting, then it's nice to have getters/setters for the basic fields as well to maintain consistent code style.
Here's a good article on it:
https://dzone.com/articles/getter-setter-use-or-not-use-0
Let's have an example:
public class Example {
private String firstName;
private String lastName;
public Example(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getFullName() {
return firstName + " " + lastName;
}
}
This class has 3 properties (firstName, lastName, fullName), but only two fields (firstName, lastName). It makes sense, because a full name can be retrieved by combining first and last name.
However, I've noticed that I call getFullName() a lot of times in my program, but I almost never call getFirstName() and getLastName(). This slows down my program, because I need to create a new string each time getFullName() is called. So, I've refactored my code to have a better performance:
public class Example {
private String fullName;
public Example(String firstName, String lastName) {
this.fullName = firstName + " " + lastName;
}
public String getFirstName() {
return fullName.split(" ")[0];
}
public String getLastName() {
return fullName.split(" ")[1];
}
public String getFullName() {
return fullName;
}
}
Now my code works faster when calling getFullName(), but slower when calling getFirstName() and getLastName(), however It's exactly what I needed. From outside the class, nothing really've changed.
As you can see by the given example, fields describe how your class uses the computer's memory, but not necessarily which properties your class has. This is why fields should be considered an implementation detail and therefore be private to a class.

Cannot resolve symbol in Java. I want to run the code of second class in the first class

I am learning Java from tutorials, and recently I faced with one problem. I need to create several classes, and I need to read all that classes through first class. Already I passed that tutorial where I understood everything and tried that thing. But now I want to create a real world app on Java, I did the exact thing which was showing in tutorial, but I am getting that error. Please, correct me where I have mistaken
Code of first class:
package com.company;
public class Email {
private String firstName;
private String lastName;
private String password;
private String department;
private String alternateEmail;
private int capacityMailbox;
// Constructor to recieve the first name and last name
public Email(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
System.out.println(em);
}// Ask for the department
// Generate a random password
// Set the mailbox capacity
// Set the alternate email
// Change the password
}
Second one:
package com.company;
public class EmailApp {
public static void main(String[] args) {
// write your code here
Email em = new Email("John", "Smith");
}
}
Screenshotes:
Thanks
You can use System.out.println(this) in constructor. It means that you will print created instance to console. And also don't forget to override toString() method - because if you don't override it, you will get object's name with hashcode.
Hope this code will help you to reach the goal:
public class Email {
private String firstName;
private String lastName;
private String password;
private String department;
private String alternateEmail;
private int capacityMailbox;
// Constructor to recieve the first name and last name
public Email(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
System.out.println(this);
}
// Ask for the department
// Generate a random password
// Set the mailbox capacity
// Set the alternate email
// Change the password
#Override
public String toString() {
return "Email{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
'}';
}
}
Another solution. Just override toString of Email class. And put printing of em to main method.
public class Email {
private String firstName;
private String lastName;
private String password;
private String department;
private String alternateEmail;
private int capacityMailbox;
// Constructor to recieve the first name and last name
public Email(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
// Ask for the department
// Generate a random password
// Set the mailbox capacity
// Set the alternate email
// Change the password
#Override
public String toString() {
return "Email{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
'}';
}
}
Main class:
public class EmailApp {
public static void main(String[] args) {
// write your code here
Email em = new Email("John", "Smith");
System.out.println(em);
}
}
The constructor of your Email Class does not have a variable called em.
You should put System.out.println(em) into the Main method of your EmailApp class.
The object reference "em" has no scope in first class i.e. class Email.
make these following two changes and compare your code. you will understand where you went wrong.
//-----------------------------------------------------change 1
public Email(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
and in second class:
//---------------------------------------------change 2
public class EmailApp {
public static void main(String[] args) {
// write your code here
Email em = new Email("John", "Smith");
System.out.println(em.firstname);
System.out.println(em.lastname);
}
}
and make all member variables public for now. You will make it private when you understand "getters and setters" concept.

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);
}
}

Get and set to private variables in java

Good day,
I am new to JAVA'm learning this language and what I have learned it seems a fantastic language. My question is in relation to the following:
Suppose I have a class like this:
public class Person{
private String firstName;
private String lastName;
private int age;
private String entireName;
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;
}
public String getEntireName() {
return entireName;
}
public void setEntireName(String entireName) {
this.entireName = entireName;
}
public static void Main(String args[]){
Person person = new Person();
person.setFirstName("Jhon");
person.setLastName("Adams");
person.setAge(20);
//Atention this line
person.setEntireName(person.getFirstName()+person.getLastName());
}
}
The language allows me to do this: person.setEntireName(person.getFirstName()+person.getLastName());
and it works fine however I would like to know how is best to do this, how it behaves at the object level and how high or low the performance.
Thank you ..
What you do is perfectly valid, but not very logical. Why not just drop the setEntireName() since it just combines two existing fields?
public String getEntireName() {
return firstName + " " + lastname;
}
This is valid. There is no performance difference, becasue JIT compiler optimize this code if needed (simply replace method with fields access).
Typically it is easier to eliminate the entireName property and its setter, and use the getter to perform the concatenation like so:
public String getEntireName() {
return firstName + " " + lastName;
}
This is also easier to maintain than updating entireName every time firstName or lastName is changed.

Getters, Setters, Constructors and their parameters

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.

Categories

Resources