I have 2 differents programs that use class and class child.
In both of the program I use private field. But in the first program that has for parent class "Car" I have no problem with private field, the children can has access to. But in the second program that has "Hamburger" for parent class, the children can not has acces to the fields :
First program (the program is working)
public class Car {
private boolean engine;
private int cylinders;
private String name;
private int wheels;
public Car(int cylinders, String name) {
this.cylinders = cylinders;
this.name = name;
this.wheels = 4;
this.engine = false;
}
}
public class Mitsubishi extends Car {
public Mitsubishi() {
super(5, "Mitsubishi");
}
}
Second program (not working)
public class Hamburger {
private String name;
private String meat;
private double price;
private String breadRollType;
private String addition1;
private String addition2;
private String addition3;
private String addition4;
public Hamburger(String name, String meat, double price, String breadRollType) {
if (price < 0) {
price = 0;
}
this.name = name;
this.meat = meat;
this.price = price;
this.breadRollType = breadRollType;
this.addition1 = "none";
this.addition2 = "none";
this.addition3 = "none";
this.addition4 = "none";
}
}
public class DeluxeBurger extends Hamburger{
public DeluxeBurger() {
super("Deluxe Burger", "Steak", 19.10, "Chic bread");
}
}
I have seen that I can use protected and it's fix the probelem, but I don't know why I have to use protected on the second program (with the Hamburger) but not on the first (with the Car).
I copy your code and past to my project and see your problem.
i dont know Why, maybe its a bug. but if you create new package and drop this two class into new package Your problem will be solved and you will not see this problem again. It was interesting for me.
thanx
I have this condition (property rent system, rent is counted per night)
Owner has one or more property. Property has description, price, and isOccupied attribute.
The property can be: hotel (with 3 room types), flat/apartment, and house for homestay.
Through a registry function, a customer can order one or more property available at certain date.
Here are the pre-defined conditions for registry function:
There are 2 registered owners and customers in the system.
Owner 1 has 10 hotel rooms (standard type) for US$30 per night and 3 hotel rooms (suite type) for US$60 per night.
Owner 2 has 3 apartments for US$70 per night and 5 homestay house for US$20 per night.
Customers can rent one or more owner's property for a certain date.
To model the property, I use inheritance concept. For now, it looks something like this.
Property.java
public class Property {
private String description;
private int propertyPrice;
private String ownerName; // should it be here? or should it be made in another class?
private boolean isOccupied;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getPropertyPrice() {
return propertyPrice;
}
public void setPropertyPrice(int propertyPrice) {
this.propertyPrice = propertyPrice;
}
}
Hotel.java
public class Hotel extends Property {
private String[] roomType;
private int[] roomCount;
public Hotel(){
this.roomType = new String[]{"Standard", "Deluxe", "Suite"};
this.roomCount = new int[]{0, 0, 0};
}
public String[] getRoomType() {
return roomType;
}
public void setRoomType(String[] roomType) {
this.roomType = roomType;
}
public int[] getRoomCount() {
return roomCount;
}
public void setRoomCount(int[] roomCount) {
this.roomCount = roomCount;
}
}
Apartment.java
public class Apartment extends Property {
private int roomCount;
public int getRoomCount() {
return roomCount;
}
public void setRoomCount(int roomCount) {
this.roomCount = roomCount;
}
}
Homestay.java
public class HomestayRoom extends Property {
private String parentName;
public String getParentName() {
return parentName;
}
public void setParentName(String parentName) {
this.parentName = parentName;
}
}
What makes me confused is, how can I define the pre-defined conditions for registry to model owner-property relation? Should I make the owner at another class? If so, how can I relate the properties and its owner?
Most of what you have done is correct, but you could also have a property type enum
public enum PropertyType{
HOTEL,APARTMENT,HOMESTAY
}
Now you're super class would be
public class Property {
private String description;
private int propertyPrice;
private String ownerName;
private boolean isOccupied;
private PropertyType pt;
....
}
A constructor for hotel would be
public Hotel(){
this.roomType = new String[]{"Standard", "Deluxe", "Suite"};
this.roomCount = new int[]{0, 0, 0};
super(PropertyType.HOTEL);
}
Similarly you could have constructors for Homestay and Apartment, with the extra line of super(PropertyType.HOMESTAY) and super(PropertyType.APARTMENT) respectively.
Related to my previous thread, i want to print an output like this:
bookId = "1234" (String)
bookName = "Machine Learning" (String)
price = $20 (int)
ratings = (array of object)
rater = a, score = 5
rater = b, score = 3
But this time, i tried to use an OOP manner.
So first, i made a POJO class called ProductView, the class will be look like this:
public class ProductView {
// field
private String bookId;
private String bookName;
private int price;
private List<Ratings> ratings;
// a constructor i tried to make
public ProductView(String bookId, String bookName, int price, List<Ratings> ratings) {
this.bookId = bookId;
this.bookName = bookName;
this.price = price;
this.ratings = ratings;
}
public String getBookId() {
return bookId;
}
public void setBookId(String bookId) {
this.itemId = itemId;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public Ratings getRatings() {
return ratings;
}
public void setRatings(Ratings ratings) {
this.ratings = ratings;
}
}
After that, i made a class called Ratings with the following field:
public class Ratings {
private String rater;
private int score;
public Ratings(String rater, int score) {
this.rater = rater;
this.score = score;
}
}
And finally, i made a Main Class called Main:
public class Main {
public static void main(String[] args) {
}
}
In the Main Class, i want to create an instance of the ProductView class and give it some value.
But i don't know how to do it with a list object param in my constructor.
Anyone can give me some insight?
first:
List is an interface, you should pass an implementation of list such as ArrayList or similar
second:
you have a compilation error in ProductView -> SetBookId, in this.itemId you don't have itemId as member or constructor parameter
furthermore, in get/set rating you need to pass and return list of Ratings.
nameing:
Ratings is actually just a Rating, you can make a new class of List or just use the Rating as is but change the name
now for your Question:
you can initialize first the list with objects and then send it to the constructor
such as:
List<Ratings> ratings = new ArrayList<>();
ratings.add(new Ratings("rater",5));
ratings.add(new Ratings("rater2",6));
ProductView productView = new ProductView("bookId","bookName",1,ratings);
Or, just initialize the ArrayList in the Constructor, the first way is preferable:
ProductView productView1 = new ProductView("bookId","bookName",1,
new ArrayList<Ratings>(Arrays.asList(new Ratings("rater",5), new Ratings("rater2",6))
));
hopefully, this answers your question
same as DodgyCodeException mentioned in the comments.
I'm using DynamoDB and I would like to store the enum's String values instead of the enum itself.
For instance, I have this enum:
public enum Source {
BREACH("breach"),
LEAKAGE("leakage");
private final String desc;
Source(String desc) { this.desc = desc; }
public String desc() { return desc; }
}
...and this "entity":
#DynamoDBTable(tableName = "Alerts")
public final class Alert implements Serializable {
private static final long serialVersionUID = 4012517315640518044L;
#DynamoDBHashKey(attributeName = "AlertId") // Partition Key or Hash Attribute
private String alertId;
#DynamoDBTypeConvertedEnum
#DynamoDBAttribute(attributeName = "Source")
private Source type;
// Constructor(s), Getter(s), Setter(s), ToString, etc...
}
With the #DynamoDBTypeConvertedEnum annotation, the value that gets saved is BREACH, but I want breach.
{
"AlertId": { "S": "a083168d-cb23-4ec8-ab80-a1c16955c4b8" },
"Source": { "S": "BREACH" },
...
"CreatedAt": { "S": "2017-05-03T14:07:36.395Z" }
}
Any clues? I did try "converters" (not fully, I couldn't make it work though) but I think I have to end up doing one for each enum type since they are all different.
You can code the Alert class like this i.e. define the attribute as String and design the getter and setter to send/receive enum object (i.e. Source).
Alert class:-
#DynamoDBTable(tableName = "Alerts")
public final class Alert implements Serializable {
private static final long serialVersionUID = 4012517315640518044L;
private String alertId;
private String type;
#DynamoDBHashKey(attributeName = "AlertId")
public String getAlertId() {
return alertId;
}
#DynamoDBAttribute(attributeName = "Source")
public Source getType() {
if (type != null)
return Source.valueOf(type);
else
return null;
}
public void setAlertId(String alertId) {
this.alertId = alertId;
}
public void setType(Source type) {
this.type = type.desc();
}
}
Create Alert:-
Stores the value as expected on database table. The get item from DynamoDB table also works fine.
public Boolean createAlert(String alertId, Source source) {
DynamoDBMapper dynamoDBMapper = new DynamoDBMapper(dynamoDBClient);
Alert alert = new Alert();
alert.setAlertId(alertId);
alert.setType(source);
dynamoDBMapper.save(alert);
return true;
}
Override toString() this should work.
public enum Source {
BREACH("breach"),
LEAKAGE("leakage");
private final String desc;
Source(String desc) { this.desc = desc; }
public String desc() { return desc; }
#Override
public String toString() { return desc; }
}
I'm deserializing a json object like this:
class Offer
{
private Category category;
private String description;
private String discount;
private Date expiration;
private Date published;
private String rescinded_at;
private String title;
private Date valid_from;
private Date valid_to;
private String id;
private Business business;
private Location location;
private Long distance;
public String getDescription() {
return String.format("[Offer: description=%2$s]", description);
}
#Override
public String toString()
{
return String.format(
"[Offer: category=%1$s, description=%2$s, discount=%3$s, expiration=%4$s, published=%5$s, rescinded_at=%6$s, title=%7$s, valid_from=%8$s, valid_to=%9$s, id=%10$s, business=%11$s, location=%12$s, distance=%13$s]",
category, description, discount, expiration, published, rescinded_at, title, valid_from, valid_to, id,
business, location, distance);
}
}
As you can see, whenever there's a nested object I just refer to a class that has a toString() method for that particular nested json object. My question is: when the json object contains an array, which in my case just looks something like this:
"draws":[
"Hair Cut",
"Blow Dry",
"Blow Dry Treatment"
]
...how do I use format.toString() to deserialize this array and then put it in my Offer toString()?
Let's clarify the meaning of two terms.
Serialize: To convert an object to a sequence of bytes.
Deserialize: To parse (serialized data) so as to reconstruct the original object.
So #LuxuryMode, when you said "deserialize", did you mean "serialize"?
Assuming this is the case...
Note that your toString implementation does not currently properly generate a JSON object or array, or anything else that is valid JSON.
I recommend not using toString or any other hand-written implementation to serialize objects to JSON (or to XML or to bytes). If possible, use an API like Gson or Jackson (or XStream or the Java Serialization API).
The following example serializes a single Offer object.
// output:
// {
// "category":
// {
// "name":"category_1",
// "type":1
// },
// "description":"description_1",
// "discount":"discount_1",
// "expiration":
// {
// "value":123
// },
// "published":
// {
// "value":456
// },
// "rescinded_at":"rescinded_at_1",
// "title":"title_1",
// "valid_from":
// {
// "value":789
// },
// "valid_to":
// {
// "value":987
// },
// "id":"id_1",
// "business":
// {
// "name":"business_name_1",
// "opening_date":
// {
// "value":654
// }
// },
// "location":
// {
// "latitude":111,
// "longitude":222
// },
// "distance":333
//}
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class Foo
{
public static void main(String[] args)
{
Offer offer = new Offer(
new Category("category_1", 1),
"description_1",
"discount_1",
new Date(123),
new Date(456),
"rescinded_at_1",
"title_1",
new Date(789),
new Date(987),
"id_1",
new Business("business_name_1", new Date(654)),
new Location(111, 222),
new Long(333));
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
Gson gson = gsonBuilder.create();
String offerJson = gson.toJson(offer);
System.out.println(offerJson);
}
}
class Offer
{
private Category category;
private String description;
private String discount;
private Date expiration;
private Date published;
private String rescindedAt;
private String title;
private Date validFrom;
private Date validTo;
private String id;
private Business business;
private Location location;
private Long distance;
Offer(Category category,
String description,
String discount,
Date expiration,
Date published,
String rescindedAt,
String title,
Date validFrom,
Date validTo,
String id,
Business business,
Location location,
Long distance)
{
this.category = category;
this.description = description;
this.discount = discount;
this.expiration = expiration;
this.published = published;
this.rescindedAt = rescindedAt;
this.title = title;
this.validFrom = validFrom;
this.validTo = validTo;
this.id = id;
this.business = business;
this.location = location;
this.distance = distance;
}
}
class Category
{
private String name;
private int type;
Category(String name, int type)
{
this.name = name;
this.type = type;
}
}
class Date
{
private long value;
Date(long value)
{
this.value = value;
}
}
class Business
{
private String name;
private Date openingDate;
Business(String name, Date openingDate)
{
this.name = name;
this.openingDate = openingDate;
}
}
class Location
{
private int latitude;
private int longitude;
Location(int latitude, int longitude)
{
this.latitude = latitude;
this.longitude = longitude;
}
}
This next example takes the JSON output from the previous example, and deserializes it back into a Java Offer object. You can add toString and/or equals implementations to verify that all of the attributes are populated as expected, but note that the toString method is not used by Gson during deserialization or serialization.
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
Gson gson = gsonBuilder.create();
String offerJson = gson.toJson(offer);
Offer offerDeserialized = gson.fromJson(offerJson, Offer.class);
To serialize an array of Offer objects is similarly simple.
Offer offer1 = new Offer(
new Category("category_1", 1),
"description_1",
"discount_1",
new Date(123),
new Date(456),
"rescinded_at_1",
"title_1",
new Date(789),
new Date(987),
"id_1",
new Business("business_name_1", new Date(654)),
new Location(111, 222),
new Long(333));
Offer offer2 = new Offer(
new Category("category_2", 2),
"description_2",
"discount_2",
new Date(234),
new Date(567),
"rescinded_at_2",
"title_2",
new Date(890),
new Date(876),
"id_2",
new Business("business_name_2", new Date(543)),
new Location(444, 555),
new Long(666));
Offer[] offers = new Offer[] {offer1, offer2};
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
Gson gson = gsonBuilder.create();
String offersJson = gson.toJson(offers);
System.out.println(offersJson);
This final example takes the JSON array output from the previous example and deserializes it back into an array of Offer objects.
Offer[] offersDeserialized = gson.fromJson(offersJson, Offer[].class);