Newbie need help understanding java code - java

I'm very new to the java programming language and I would really like some help understanding what the following code is doing. I have a pretty decent understanding of what is going on within the Main class. My problem is what part "this._" plays within the code. How exactly are the names getting transferred? This is not homework just self study. The exercise can be found here:http://www.learnjavaonline.org/Functions Also, suggested reading would be great! Thanks!
class Student {
private String firstName;
private String lastName;
public Student(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public void printFullName(){
System.out.println(this.firstName+" "+this.lastname);
}
}
public class Main {
public static void main(String[] args) {
Student[] students = new Student[] {
new Student("Morgan", "Freeman"),
new Student("Brad", "Pitt"),
new Student("Kevin", "Spacey"),
};
for (Student s : students) {
s.printFullName();
}
}
}

this references to the object your is working in.
so in your sample
class Student {
private String firstName;
private String lastName;
public Student(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public void printFullName(){
System.out.println(this.firstName+" "+this.lastname);
}
}
this.firstName is the private String firstName; value in your object/class
and firstName is the method parameter.
the this is required in this example as it otherwise would be firstName = firstName and that would assign the value of your parameter to itself.

The reason this is used is because the variables firstName and lastName are shadowed by the constructor parameters. See the differences with this:
class Student {
private String firstName;
private String lastName;
public Student(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
Compared to without this:
class Student {
private String myFirstName;
private String myLastName;
public Student(String firstName, String lastName) {
myFirstName = firstName;
myLastName = lastName;
}
You use this to reference variables in the current object.

See that variables with "this" are in constructor. This means THE OBJECT, so in the lines:
public Student(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
you assing variable to your object. Remember that these variables are in constructor !

Related

How do you create a java object that uses a variable from another class?

How do you create a java object that uses a variable from another class, or calls the entire constructor?
For example, accountNumber, firstName, lastName, phone are all variables passed in address is comprised of street, city, state, and zip, and has already been created:
Address address = new Address(street, city, state, zip);
Data is comprised of only megabytes, and has already been created:
Data data = new Data(megabytes);
This is what I have for the customer object:
Customer customer = new Customer(accountNumber, firstName, lastName, address, phone, data);
This is supposed to be an "overloaded constructor", but I don't understand what that means.
This is the constructor I have so far:
public Customer(String accountNumber, String firstName, String lastName, Address address, int phone, Data megabytes)
{
this.accountNumber = accountNumber;
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.phone = phone;
this.megabytes= megabytes;
}
I get the error:
The constructor Customer(String, String, String, Address, int, Data) is undefined
At a glance everything seems fine. I hoped you saved the file before compiling.
Since you mentioned that you didn't understand what an overloaded constructor is, I'll try my best to explain that.
An overloaded constructor has the same constructor name but it differs from other constructors in the following ways -
It has different number of formal arguments
The order of type of formal parameters of the constructor are different
Here is an example -
public class Customer {
private String firstName;
private String lastName;
private int phoneNumber;
public Customer() {
// default constructor
}
public Customer(String firstName) {
this.firstName = firstName;
}
public Customer(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public Customer(String firstName, String lastName, int phoneNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.phoneNumber = phoneNumber;
}
public Customer(int phoneNumber, String firstName, String lastName) {
this.phoneNumber = phoneNumber;
this.firstName = firstName;
this.lastName = lastName;
}
// This is not an overloaded constructor as there is already a constructor of type
// Customer(String, String)
// public Customer(String lastName, String firstName) {
// this.lastName = lastName;
// this.firstName = firstName;
// }
}

Adding arraylist object to combobox [duplicate]

This question already has answers here:
How do I populate a JComboBox with an ArrayList?
(8 answers)
Closed 6 years ago.
I've created a JCombobox using Netbeans drag and drop.
I have an ArrayList<Person>.
How do I automatically add the FirstName of the Person into the combobox.
The code generated by Netbeans cant be edited in Source view.
Step 1: Lets say you have the following Person class.
Person.java
public class Person {
private int id;
private String firstName;
private String lastName;
public Person() {
}
public Person(int id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
#Override
public String toString() {
return firstName;
}
}
Step 2: Create the instance of JComboBox and set the model.
java.util.List<Person> list=new java.util.ArrayList<Person>();
list.add(new Person(1, "Sanjeev", "Saha"));
list.add(new Person(2, "Ben", "Yap"));
JComboBox<Person> comboBox = new JComboBox<Person>();
comboBox.setModel(new DefaultComboBoxModel<Person>(list.toArray(new Person[0])));
Step 3: Run your program.
public class PersonBox{
List<Person> person= new ArrayList<Person>();
JCombobox box; //=new JCombobox(...) ?
//used to add a new Person to the box
public void addPerson(Person person){
person.add(person);
/*
*gets the lass element in the list and adds the first
*name of this specific element into the box
*/
box.addItem(person.get(person.size()-1).getFirstName());
}
}
public class Person{
String firstName,sureName;
public Person(String firstName, String sureName){
this.firstName = firstName;
this.sureName = sureName;
}
public String getFirstName(){
return this.firstName;
}
public String getSureName(){
return this.sureName;
}
}

Overloaded constructors in a class

I'm doing a project with overloaded constructors in a class and I'm a little stuck, below is what I'm supposed to be doing with the overloaded constructors:
"One that allows first, middle, and last names to be passed as Strings with an int for age
One that accepts a Name object reference, and an age as an int
Make a new Name inside Person, copying the references for the parts of the name."
I'm not quite sure what to do with my code, here is what I got:
public class Person {
int age;
Name aPersonHasAName;
Name newPerson = new Name();
public Person(String firstName, String middleName, String lastName, int age) {
newPerson.firstName = firstName;
newPerson.middleName = middleName;
newPerson.lastName = lastName;
}
public Person(Name aPersonHasAName, int age) {
}
public void details() {
System.out.println(aPersonHasAName + " age: " + age);
}
}
I'm just lost as to what I'm supposed to be typing. I believe I've done the first overloaded constructor, but I am new to this.
So what should I be doing to make this work with overloaded constructors?
I think having the code from the other two classes might help.
Here is PersonTester:
public class PersonTester {
public static void main(String[] args) {
Person person1 = new Person("a1", "b1", "c1", 11);
Person person2 = new Person(new Name("a2", "b2", "c2"), 22);
Person person3 = new Person(new Name("a3", "c3"), 33);
Person person4 = new Person(new Name("a4"), 44);
Person person5 = new Person(new Name(), 55);
System.out.println(person1.details());
System.out.println(person2.details());
System.out.println(person3.details());
System.out.println(person4.details());
System.out.println(person5.details());
}
}
Then here is the Name class:
public class Name {
String firstName;
String middleName;
String lastName;
public Name(String firstName, String middleName, String lastName) {
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
}
public Name(String firstName, String lastName) {
this(firstName, "", lastName);
}
public Name(String firstName) {
this(firstName, "", "");
}
public Name() {
this("", "", "");
}
public String getLastName() {
return lastName;
}
public String getMiddleName() {
return middleName;
}
public String getFirstName() {
return firstName;
}
public String getFullName(String nameString) {
StringBuilder build = new StringBuilder();
build.append(nameString);
build.deleteCharAt(nameString.length() - 1);
build.insert(0, build.hashCode());
return build.toString();
}
}
The problem I am having now is the error message in PersonTester which is: The method println(boolean) in the type PrintStream is not applicable for the arguments (void)
I just need to know what in which class needs to be fixed to make it work.
I am very new to Java and object oriented programming.
So far so good. But eventually you'll reach a point where you duplicate a fair bit of code.
The constructor
public Person(String firstName, String middleName, String lastName, int age) {
is the most comprehensive one in the sense that it takes in all the possible data.
With the other constructors, say one that takes a last name and an age, you can use delegating constructors:
public Person(String lastName, int age) {
this(null, null, lastName, age); /*calls the other constructor*/
}
If you can't make such an assumption then you'll need to split up the name string by hand.
Updating your code:
public Person(String firstName, String middleName, String lastName, int age) {
newPerson.firstName = firstName;
newPerson.middleName =
newPerson.lastName = lastName;
this.age = age; //<---- was missing in your code
}
And your second contructor may look like this:
public Person(Name aPersonHasAName, int age) {
this.newPerson = aPersonHasAName;
this.age = age;
}
These contructors are implemented as you needed.
Notice that you already done your overloading, if you got multiple constructors with not the same titles you contructors overloading
public class Person {
int age;
Name aPersonHasAName;
public Person(String firstName, String middleName, String lastName, int age) {
aPersonHasAName = new Name();
aPersonHasAName.firstName = firstName;
aPersonHasAName.middleName = middleName;
aPersonHasAName.lastName = lastName;
this.age = age;
}
public Person(Name aPersonHasAName, int age) {
this.aPersonHasAName = aPersonHasAName;
this.age = age;
}
public void details() {
System.out.println(aPersonHasAName + " age: " + age);
}
}
I guess it also depends on if Name has a constructor for firstName, middleName, lastName

Read and Add Text File to an ArrayList of Object in Java

I have a text file "addresses.txt" that holds information about a person. I have created a Person class and I need to read and store the information from this text file into an ArrayList.
My error is when trying to read the text file I can not add it to my ArrayList because of the String arguement. Really lost at this point I know it may be a simple solution but I just cant figure it out.
Here is some of my Person class if needed:
public class Person {
private String firstName;
private String lastName;
private String phoneNumber;
private String address;
private String city;
private String zipCode;
private static int contactCounter = 0;
public Person(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
contactCounter++;
}
public Person(String firstName, String lastName, String phoneNumber){
this.firstName = firstName;
this.lastName = lastName;
this.phoneNumber = phoneNumber;
contactCounter++;
}
public Person(String firstName, String lastName, String address, String city, String zipCode){
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.city = city;
this.zipCode = zipCode;
contactCounter++;
}
Here is my main class:
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
public class Rolodex {
public static void main(String[] args) {
ArrayList <Person> contactList = new ArrayList <Person> ();
readFile(contactList);
}
public static void readFile(ArrayList <Person> contactList){
try{
Scanner read = new Scanner(new File("addresses.txt"));
do{
String line = read.nextLine();
contactList.add(line); //MY ERROR IS HERE. I know why its happening just not how to fix.
}while(read.hasNext());
read.close();
}catch(FileNotFoundException fnf){
System.out.println("File was not found.");
}
}
You try to add String line into Person array.
You can't cast String to Person.
Fix:Try to implement some kind of line parser
eg. Your line looks like this "adam;bra;555888666;" you have to parse this string using line.split(";")
it creates you array of Strings (String[]) now just use your constructors to create Person and add him into contactList
eg.
contactList.add(New Person(parsedString[0], parsedString[1], parsedString[2]));
Instead of using a text file, you should use a JSON file. And with the GSON library, it's more easy to get and write data in files...

Why does this output wrong (get/set methods)

Just going through get/set methods and I'm having trouble with my output. Instead of displaying the First/Last name of the object it is displaying null/null.
Could anyone offer any insight, i'm not familiar with get/set methods.
Code
public class Person {
private String firstName;
private String lastName;
public Person (String a, String b){
a = firstName;
b = lastName;
}
public String getfirstName(){
return firstName;
}
public void setfirstName(){
this.firstName = firstName;
}
public String getlastName(){
return lastName;
}
public void setlastName(){
this.lastName = lastName;
}
public String toString() {
String s = "First name:" + firstName + "Last name:" + lastName;
return s;
}
}
This is my class just to create the object and run to toString method
public class PersonDriver {
public static void main(String[]args){
Person p1 = new Person ("Thomas", "Brown");
System.out.print(p1.toString());
}
}
You need to assign the parameters to the instance variables and not the reverse. What you're doing currently is reassigning a and b which were passed to the constructor, whereas you need to assign the values of a and b to the firstName and lastname fields of the class.
public Person (String a, String b){
firstName = a;
lastName = b;
}
You inverted the variables within your constructor
You need Change below code
public Person (String a, String b){
a = firstName;
b = lastName;
}
to
public Person (String a, String b){
firstName = a;
lastName = b;
}
Primarily setters has to be
public void setFirstName(String firstName){
this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
Your setters should take an argument - the value to be set. Your constructor should assing the values of the arguments to the class properties not the other way round.
I think the constructor has to be like
public Person (String a, String b){
firstName = a;
lastName = b;
}
You need to swap the variabels. You assign the value of the object the parameters.
public Person (String a, String b){
firstName= a;
lastName= b;
}
Also your set method are useless without parameters :
public void setlastName(String parameter){
this.lastName = parameter;
}
You sure your methods shouldn't be more in line with this?
public class Person {
private String firstName;
private String lastName;
public Person (String a, String b){
firstName=a;
lastName=b;
}
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 toString() {
String s = "First name:" + firstName + "Last name:" + lastName;
return s;
}
}
You need to pass the setter methods the values you would want to set the variables to. Apart from that, like the others mentioned, you swapped the variable names in the constructor. :)

Categories