Wondering if I'm doing this immutability exercise correctly - java

My professor just went over mutable and immutable, and gave us this coding exercise to complete.
1) Create a Customer object called customer with initial values of 1 and "Cust1"
respectively.
2) Display the customer object to the screen using the toString() method.
3) Create a String object reference called name and assign to it the customer's name.
4) Assign the value "Bo Beep" to the object reference name.
5) Display the customer object to the screen using the toString() method.
The output should look like this.
Customer{id=1, name=Cust1}
Customer{id=1, name=Cust1}
I currently have 2 seperate classes, here they are. I'm not sure whether I'm doing it correctly, I think I have done the first 2 right, but I'm not sure about 3-5.
Any input is helpful, thanks!
Here's my main class,
package hw01;
public class Main {
static Customer customer = new Customer(1, "cust1");
static Customer name = new Customer(1, "Bo Peep");
public static void main(String[] args) {
System.out.println(customer);
System.out.print(customer);
}
}
And here's my Customer class.
package hw01;
public class Customer {
private int id;
private String name;
public Customer() {
}
public Customer(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
#Override
public String toString() {
return "Customer{" + "id=" + id + ", name=" + name + '}';
}
}

Sounds like for #3 it should be something like this:
String name = customer.getName();
and then #4 would be:
name = "Bo Peep";
The goal of the exercise I think is to demonstrate that even though name and customer.name reference the same String object, since a String is immutable when you set name = "Bo Peep"; you're not changing the actual String object but instead creating and referencing a new String object. If the String were mutable then printing the customer the 2nd time would display the name "Bo Peep".

Related

Having troubles creating this object

I'm very new to java, and trying to grasp making an object with two different values.
I'm trying to create a Customer object called customer, with the initial values of 1 and cust1, and then display the customer object to the output with toString()
Thanks for any help in advance.
Here's what I have currently.
public class Customer {
private int id;
private String name;
public Customer(int id, String name) {
this.id = id;
this.name = name;
Customer customer = new Customer(1, "cust1");
}
You have no entry point to your program, which should look like this in your class
public static void main(String[] args)
{
//objects created here
}
You also create a Customer object as a member of your Customer class which means every Customer object contains another.
You can't set Customer members like this
Customer customer = new Customer(); //you also don't have a no argument constructor
customer = 1; //how would it know where to put this 1?
customer = cust1; //same as above
it would be like this (if they were in the right place, as mentioned above)
Customer customer = new Customer(); //if using this method you will need a no argument constructor
customer.id = 1;
customer.name = cust1;
or like this
new Customer(1,"cust1");
In Summary
You need an entry point
You are creating Customer with a no argument constructor but you only have one constructor which has two arguments
You are -for some reason- creating a Customer inside every Customer
You are not setting members of your Customer object in the correct (or even in a valid) way
Don't create a new object instance within a classes constructor — this will result in a StackoverFlowException.
public class Customer {
private final int id;
private final String name;
public Customer(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}
In a separate class you can simply create a new instance by using
Customer customer = new Customer(1, "Name");

How to override?

package wr3;
public class Person {
private String name;
private String id;
private String bday;
private String address;
public String getName(){
return name;
}
public String getID(){
return id;
}
public String getBday(){
return bday;
}
public String getAdd(){
return address;
}
public void equals(){
super.equals(id);
}
#Override
public String toString(){
return(name + bday + id + address);
}
}
package wr3;
public class Test {
public static void main(String[] args){
String name = "Claude Rhay Torre";
String name2 = "Bea Señerpida";
String id = "10302993";
String id2 = "11102825";
String bday = "06/201993";
String bday2 = "11/17/1994";
String address = "BF Better Living Basak LLC";
String address2 = "F Martyr St Poblacion LLC";
boolean eq;
System.out.println(name.toString());
System.out.println(id.toString());
System.out.println(bday.toString());
System.out.println(address.toString());
System.out.println();
System.out.println(name2.toString());
System.out.println(id2.toString());
System.out.println(bday2.toString());
System.out.println(address2.toString());
eq = id.equals(id2);
System.out.println("\nDo they have the same ID number? " + eq );
}
}
So I have this code.
And I also have this problem.
A. Object class
Study the Object class in the java.lang package.
Understand all its methods.
Create a Person class with the requirements:
a. Implement encapsulation
b. The fields are: name, ID (identification number), birthday, and
address.
c. A method that will override the equals( ) method of Object class.
Two persons are equal if they have the same id.
d. A method that will override the toString( ) method of Object
class. It displays the id, name, birthday, and address of a Person
object.
Create a test class to create Person objects and call the equals( ) and toString( ) methods appropriately.
My question is, are these two classes even related?
What I mean, is my "toString" and "equal" method called on my Test class the one that is in my Person's class? Or is it the "toString" and "equal" methods on the Object class?
How can I override the equals and toString class in the Object class?
When inheriting a method from another class (such as public String toString() from Object), all you have to do to override it is define your own public String toString() in your class. You have actually done that in your code and you have successfully overridden toString() for all instances of Person.
The reason you're not seeing the result you might expect is that the toString() and equals() methods you are calling are from the String class, not from your Person class. This is because you are calling them on String objects, not Person objects - and those two classes are not related hierarchically (apart from their common Object ancestor).
Your Test could be like this, instead:
Person p1 = new Person();
p1.name = "Claude Rhay Torre";
p1.id = "10302993";
p1.bday = "06/20/1993";
p1.address = "BF Better Living Basak LLC";
Person p2 = new Person();
p2.name2 = "Bea Señerpida";
p2.id2 = "11102825";
p2.bday2 = "11/17/1994";
p2.address2 = "F Martyr St Poblacion LLC";
System.out.println(p1.toString());
System.out.println(p2.toString());

Java extracting individual data from an object list

I have a Java Class like this:
public class Employee {
String Name;
int Id;
int Age;
void setName(String tempVal) {
Name = tempVal;
System.out.println(Name);
System.out.println("\n");
}
void setId(int parseInt) {
Id = parseInt;
System.out.println(Id);
System.out.println("\n");
}
void setAge(int parseInt) {
Age = parseInt;
System.out.println(Age);
System.out.println("\n");
}
}
Now I want to parse a employees.xml file using SAXParser using the code in the link: http://totheriver.com/learn/xml/xmltutorial.html#5.2
The problem is when I am adding the tempEmp to the list and accessing the list to print its value in printData() method, the output is something like:
No of Employees '3'.
Employee#140de537
Employee#1c43882a
Employee#15a08be5
Now, how do I extract the name, age and id of the employee individually?
I guess you are adding the Employee object to the list and printing the objects directly from list.If you dont override the toString() method, it will call the toString() method of Object class(superclass of all class), which will be returing the classname#hashcode(hashcode of object).If you want to print some data from your class, you need to override toString() method in your class and return the format you require.
You have to implement a toString() method in the Employee class for it to be displayed correctly, something along these lines:
#Override
public String toString() {
return Id + " " + Name + " " + Age;
}
Also, remember that in Java attribute names should start with a lowercase character, not uppercase.
You want to add some getter methods.
You should also check out the code conventions for Java - some of your variables start with an uppercase letter where they should not.
To get each value individually, you need to add a few get methods
public String getName()
{
return Name;
}
public int getAge()
{
return Age;
}
public int getId()
{
return Id;
}

Java, I need help instantiating an object

Hello I'm new to Java. I'm trying to create a object and pass name through it. I don't have a clue what I'm doing wrong?.
public class Employee
{
private String name, number;
private String date;
public Employee()
{
name= "";
number = "";
date = "";
}
public Employee(String name, String number, String date)
{
setName(name);
setNumber(number);
setDate(date);
}
public void setName(String n)
{
name = n;
}
public void setNumber(String n)
{
number = n;
// you can check the format here for correctness
}
public void setDate(String d)
{
date = d;
}
public String getName()
{
return name;
}
public String getNumber()
{
return number;
}
public String getDate()
{
return date;
}
}
import java.util.Scanner;
public class TeamLeadDemo
{
public static void main(String[] args)
{
String name;
// create scanner object
Scanner keyboard = new Scanner(System.in);
// inputting data
System.out.println("Enter Name:");
name = keyboard.nextLine();
// instantiating object, HERE IS THE PROBLEM
Employee thename = new Employee(name);
// outputting data
System.out.println("Employee Name:"+thename.getName());
System.out.println("Employee Details:\n" + thename);
}
}// Function definition
What should i do??
Hey fellow newbie programmer!
Take a look at how you initialize your object:
Employee thename = new Employee(name);
Since you only give it the String name as a parameter, Java cannot initialize your Employee object because it does not have a single argument constructor!
Here are your constructors method signatures:
public Employee()
public Employee(String name, String number, String date)
One takes no arguments, and the other takes 3 arguments.
If you look at the way you initialize it, you only pass 1 argument!
You would need to create a new Constructor that has a single argument in order for your code to work. Or easier yet, you could just pass in "", "" for your number and date string values.
More experienced programmers please do not hesitate to correct my programming semantics if they are wrong. I feel like I'm using words that I do not fully understand.
You need a constructor that receives only the name that you are passing:
public Employee(String name) {
this.name = name;
this.number = "";
this.date = "";
}
Currently you only have one default constructor and one that receives all three properties.
Your Employee class has two constructors: one taking zero arguments and one taking three arguments. Yet you're attempting to construct it with one argument. That wouldn't compile.
There are two possible solutions:
Add another constructor taking one argument.
public Employee(String name) {
this.name = name;
}
Use the constructor taking three arguments and pass null through.
Employee employee = new Employee(name, null, null);
Unrelated to the concrete problem, setting values to empty strings in the default constructor and calling the setters in the second constructors is not a nice practice. In the first, just do nothing, keep them default null. In the second constructor, you should prefer setting the property directly instead of calling the setter.
You need to pass in the number and date to the constructor as well. Try:
Employee thename = new Employee(name, "", "");
Employee thename = new Employee(name);
You have no constructor that takes only one String
If you have some very very strong reasons not to use Employee thename = new Employee(name, "", "");, you may try "varargs"
As :
public class Employee {
String fname="";
String lname="";
public Emp(String... attrs) {
if ( attrs.length > 1 ) {
fname = attrs[0];
lname = attrs[1];
}else if(attrs.length == 1) {
fname = attrs[0];
}
}
public String toString() {
return fname + " " + lname;
}
public static void main(String[] args){
Employee e1 = new Employee ("Test");
Employee e2 = new Employee ("Test" ,"case");
System.out.println(e1);
System.out.println(e2);
}
}
Caution : this is just to answer your question- Think before using in real world situations. Not from design/ best approach perspective. But it is different and caters to your question though ;-)

Java program error creating a Person class

Please can anyone tell me what the error is in the following piece of code?
Question is
Create a class person which has
A variable ‘name’ which stores the name of the person.
A constructor that takes a single argument that is used to initialize the name variable
A method getName() which displays the name.
A protected method setName() that takes one argument which is used to modify the name variable.
Create a subclass of the above class called student, which contains
A variable to store PRN of a student
A variable to store course the student belongs to
A method, which displays all the details of the student i.e, name, prn and course.
Program :
class Person
{
String name;
Person(String s)
{
name=s;
}
void getName()
{
System.out.println("Name is "+name);
}
void setName(String sa)
{
name=sa;
}
}
class subPerson extends Person
{
//String sa;
int Prn;
String course;
subPerson(String s,int P,String co)
{
name=s;
Prn=P;
course=co;
}
void displayal()
{
System.out.println("Name is ");
System.out.println("PRN is "+Prn);
System.out.println("course is "+course);
}
}
class Inher
{
public static void main(String args[])
{
int area,volumea;
subPerson h1 = new subPerson("Abhishek",20,"MBA");
h1.displayal();
}
}
Person's constructor takes a String. Since subPerson extends Person, its constructor will invoke a constructor of Person. By default it'll use the no-arg constructor, but since Person doesn't have one, it won't work.
Try changing subPerson's constructor to this:
subPerson(String s,int P,String co)
{
super(s);
Prn=P;
course=co;
}
I assume that compiles (I'm not going to check that), then the fundamental problem is that in the displayal() method, you don't actually print out the name...
System.out.println("Name is ");
should actually be something like
System.out.println("Name is " + name);
Aside from that, there are some problems with not following typcial java coding conventions. While the code may compile and do what is desired, most java guys will likely get hung up on "not following naming conventions" instead of trying to fix the problem because the code looks unusual.
I'd also recommend that you pay more attention to names. They matter a great deal and deserve careful thought.
"subPerson" as a class name leaves me quite cold. Aside from the poor camel case style, the assignment explicitly calls for a class Student. Why did you go with "subPerson"?
I would advise against the "displayal" (sic) method as well. The proper idiom is to override the toString() method in Object.
I'd write it like this:
/**
* Person
* User: Michael
* Date: Sep 27, 2009
* Time: 10:00:00 AM
*/
public class Person
{
private String name;
public static void main(String[] args)
{
Person s = new Student("Foo Bar", "35", "Intro To Java");
System.out.println(s);
}
public Person(String name)
{
if ((name == null) || (name.trim().length() == 0))
throw new IllegalArgumentException("name cannot be blank or null");
this.name = name;
}
public String getName()
{
return name;
}
public void setName(String name)
{
if ((name == null) || (name.trim().length() == 0))
throw new IllegalArgumentException("name cannot be blank or null");
this.name = name;
}
#Override
public String toString()
{
return "Person{" +
"name='" + name + '\'' +
'}';
}
}
class Student extends Person
{
private String prn;
private String course;
Student(String name, String prn, String course)
{
super(name);
this.prn = prn;
this.course = course;
}
#Override
public String toString()
{
return "Student{" +
"name='" + getName() + '\'' +
", prn='" + prn + '\'' +
", course='" + course + '\'' +
'}';
}
}

Categories