Could a superclass differ to subclasses? - java

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.

Related

Object to string delimited format

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

calling a function containg enum in java

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.

java - Editing child in list of parents

I've got an abstract class called customer and another classe called payCust that extends this abstract class. There is another client class that initializes a list of customers.List<Customer> custList = new ArrayList<>();
the customer class has a constructor as follows:
public Customer(String name, String email, String mag) {
this.CusEmail = email;
this.CusName = name;
this.magazine = mag;
}
payCust has the following constructor:
public PayCust(String _name, String _email, String _accountType, String _custMag) {
super(_name, _email, _custMag);
this.accountType = _accountType;
}
all the variables have public get and set methods. e.g.
public void setName(String name) {
this.CusName = name;
}
public String getName() {
return this.CusName;
}
my question is that if the custList had a PayCust added to it. how can i edit the accountType of a customer from that list?
note: email is unique to every customer
You will have to check the instance type of the object within the ArrayList and cast it for usage.
Something like this, for example:
for (Customer c : custList){
if(c instanceof PayCust){
PayCust pc = (PayCust) c;
pc.getAccountType();
}
}
You would have to cast it to a PayCust (assuming you know for a fact that it's a PayCust):
PayCust example = (PayCust) custList.get(0);
String accountType = example.getAccountType ();
...

Wondering if I'm doing this immutability exercise correctly

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".

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

Categories