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());
Related
I have set of objects of different types.
Ex : Employee emp, adress adr
These two classes have list of properties
public class Employee{
private Stringname;
private int age;
}
public class Adress {
private String HouseNo;
private string Street;
private string pin;
}
Each attribute is assigned with some 2 character value
Name (NA), age (AG), HouseNo(HN),Street(ST), pin(PN)
I need to construct a string with these data and delimit with a %
Output:
NA%Vidhya%AG%30%HN%80%ST%1st cross%PN%100100
Each class knows it own data best so I would let each class be responsible for generating the string. As I understand it the two char codes for each field are unique for each class and member and only used when generating the string so only the class would need them.
interface AttributeDescription {
String generateDescription();
}
public class Employee implements AttributeDescription {
//members...
public String generateDescription() {
return String.format(“NA%%%s%%AG%%%d”, name, age)
}
Then simply call this method for all objects implementing the interface.
AttributeDescription object = ...
String attr = object.generateDescription();
I don't think it can be generalized more than this given the requirements.
Update
It might be better to have a builder class for building the string to get a more unified behavior between classes. Here is an example
public class AttributeBuilder {
private builder = new StringBuilder();
public String getAttribute() {
return builder.toString();
}
public void add(String code, String value) {
if (value == null) {
return;
}
builder.append(code);
builder.append(‘%’);
builder.append(value);
builder.append(‘%’);
}
}
And then you would also have to implement add(...) methods for other data types in a similar fashion. The builder could then be used like
public String generateDescription() {
AttributeBuilder builder = new AttributeBuilder();
builder.add(“NA”, name);
builder.add(“AG”, age);
return builder.getAttribute();
}
Lets say we have:
1) Superclass containing a string parameter: companyName
2) Subclasses containing string parameters: firstName, lastName
If we have subClassA, subClassB, subClassC, subClassD, etc. Can these subclasses have same superclass, but with different strings companyName, or the companyName meaning/value will be the same for every subclass no matter what?
Every instance of the parent class can have a different value for companyName whether it's of a subtype or not.
public class Parent {
private final String companyName;
public Parent(String name) {
this.companyName = name; // ignoring error-checking here
}
public String getCompanyName() {
return companyName;
}
}
public class Subsidiary extends Parent {
private final String subsidiaryName;
public Subsidiary(String parentName, String subsidiaryName) {
super(parentName);
this.subsidiaryName = subsidiaryName;
}
public String getSubsidiaryName() {
return subsidiaryName;
}
}
In some client code you can call:
Subsidiary subsidiary = new Subsidiary("Holdings, Inc.", "Puppet");
System.out.println(subsidiary.getCompanyName() + " owns "
+ subsidiary.getSubsidiaryName());
You see, the child-type object inherits the accessor method getCompanyName that gives it access to the information in the parent section of the object.
I have defined a class
class Prop{
public static enum property{
NAME,
CITY,
ADDRESS;
}
private String NAME;
private String CITY;
private String ADDRESS;
public String getValue(property pro){
switch(pro){
case NAME:
return NAME;
case CITY:
return CITY;}
return null;}
}
class CallPro{
private String name;
name=Prop.getValue("");
}
I am not exactly getting how to call getValue from class CallPro.
Basically what parameters should be passed to get the desired value.
I am a beginner in java
To run this program you need a public static void main(String[]) method first. That's your entry point into any Java program. Since, you want to assign the values inside callPro, add the main() method there.
Next, you want to call getProperty() which is an instance method belonging to class prop, so you'll need to create an instance of it first using the new constructor() syntax.
class callPro {
private static String name;
private static String city;
private static String address;
public static void main(String[] args) {
// create prop instance
prop property = new prop();
// call prop's method getValue()
name = property.getValue(prop.property.CITY);
city = property.getValue(prop.property.NAME);
address = property.getValue(prop.property.ADDRESS);
// New York, John, Central Park
System.out.println(name + ", " + city + ", " + address);
}
}
Notice, how I had to make callPro's members static to be able to access them inside the main() method because that's static too. Also, note how I referenced the Enums: className.enumType.enumValue.
To be able to see the values print from the main() method, you'll also need to provide values for your prop class members as
private String NAME = "John";
private String CITY = "New York";
private String ADDRESS = "Central Park";
public String getValue(property pro) {
switch (pro) {
case NAME:
return NAME;
case CITY:
return CITY;
case ADDRESS:
return ADDRESS;
}
return null;
}
Yes, you can loop through an enum's values and retrieve your properties in a loop as
prop property = new prop();
for (prop.property prop : prop.property.values()) {
System.out.println(property.getValue(prop));
}
enumType.values() returns an enumType[] of all enumValues which can be used with a for-each loop as shown above.
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".
So, I'm working on a homework assignment, and I'm having a hard time following some of the directions, I've pasted the assignment below:
Create a hierarchy of five classes, plus one class included as a variable inside:
Person has four String variables: name, address, phone, email
Student is a subclass to Person and has one additional int variable status which takes values of 1, 2, 3, or 4 representing freshman, sophomore, junior, senior
MyDate has three int variables for year, month, and day
Employee is a subclass to Person and has one String variable office, one int variable for salary, and one MyDate variable for dateHired
Staff is a subclass to Employee and has one additional String variable for title
Faculty is a subclass to Employee and has one additional String variable for rank which takes values of Professor, Associate Professor, Assistant Professor, Instructor, and Adjunct. The data for all six classes should be private.
As for methods, you can skip the normal setters and getters if you write a single constructor that has parameters for all data and override the toString( ) method. Constructors of subclasses should use the super class constructor. The toString( ) methods of subclasses should use the toString( ) method of their super class.
The part that throws me for a loop is the idea that a single constructor can be written that will cover all the necessary parameters for the setters and getters instead of writing them in each sub-class. Is this possible? And how so?
You need to use the constructor of the superclass whilst creating the subclass. So it should be:
public class Staff extends Employee {
private String title;
public Staff(String name, String address, String phone, String email, int status, String title) {
super(name, address, phone, email, status);
this.title = title;
}
}
Use the super(/*params of super class*/) to invoke the constructor of the super class and instantiate the inherited attributes. Note that you can only call a superclass constructor as the first statement of a constructor. If you don't call a superclass constructor explicitly, a call to super() (the default constructor of the superclass) is inserted automatically by the Java compiler.
For calling the parent class's toString() use:
public String toString() {
return super.toString() + " ,title : " this.title;
}
Similarly write the constructors and toString() methods of all classes.
As for methods, you can skip the normal setters and getters if you write a single constructor that has parameters for all data and override the toString( ) method.
I think the directions mean that each class you write can have a single constructor that takes parameters for all of its data. Taking the MyDate constructor for example:
public MyDate(int year, int month, int day) {
...
}
And likewise override toString() to report all that information.
Instead of writing
public class A {
private int b;
private int c;
public void setB(int b) {this.b = b;}
public int getB() {return b;}
// same for c
}
you allowed to code
public class A {
private int b;
private int c;
public A(int b, int c) {
this.b = b;
this.c = c;
}
#Override
public String toString() {
return "[b = " + b + ", c = " + c + "]";
}
(The implementation of toString() is just an example, it just needs to print the states of all fields)
This is what you can do
Person(String name,String address,String phone,String email){
//Person constructor
this.name = name;
this.address = address;
this.phone = phone;
this.email = email;
}
public String toString(){
//toString method
return "Name: "+name+" Address: "+address+" Phone: "+phone+" Email: "+email;
}