I have an Enum which has three constants as of now. All three are having 10+ overridden methods. Is it possible to have a better design so that I can put all of them to a common class.
Updated with sample code:
public enum MyEnum {
FIRST {
#Override
public String doIt() {
return "1: " + someField; //error
}
#Override
public String getCategory() {
return "MyCategory1"; //error
}
},
SECOND {
#Override
public String doIt() {
return "2: " + someField; //error
}
#Override
public String getCategory() {
return "MyCategory2"; //error
}
},
THIRD {
#Override
public String doIt() {
return "3: " + someField; //error
}
#Override
public String getCategory() {
return "MyCategory3"; //error
}
};
private String someField;
public abstract String doIt();
public abstract String getCategory();
}
Why not try it like this:
public enum MyEnum{
FIRST(1),
SECOND(2),
THIRD(3);
private final int value;
private MyEnum(int value) {
this.value = value;
}
public String doIt() {
return value + ": " + someField;
}
public String getCategory() {
return "MyCategory" + value;
}
}
There is no need to repeat any methods, let alone to override them.
If you want specifically a class:
import lombok.AllArgsConstructor;
import lombok.Getter;
#Getter
#AllArgsConstructor
public class Category {
public static final Category FIRST = new Category(1, "MyCategory1", "someField");
public static final Category SECOND = new Category(2, "MyCategory2", "someField");
public static final Category THIRD = new Category(3, "MyCategory3", "someField");
private int categoryId;
private String category;
private String someField;
public String doIt() {
return this.categoryId +": " + this.someField;
}
}
And then just use constants:
public class TestCategory {
public static void main(String[] args) {
System.out.println(FIRST.doIt());
System.out.println(FIRST.getCategory());
}
}
Related
I have an assignment and my superclass default values always override the values I pass in the Test main method. In the debugger, i see the passing of the productNumber(1234) and productTitle("Daughter"), but then it's overridden with the default values. Any thoughts, i keep making minor changes, checking for changes, still the same results.
Product Superclass
public abstract class Product {
private int productNumber;
private String productTitle;
//Two constructors required
public Product(){
productNumber = 0;
productTitle = "";
}
public Product(int productNumber, String productTitle) {
this.productNumber = productNumber;
this.productTitle = productTitle;
}
public void setProductNumber(int productNumber) {
this.productNumber = productNumber;
}
public int getProductNumber() {
return productNumber;
}
public void setProductTitle(String productTitle) {
this.productTitle = productTitle;
}
public String getProductTitle() {
return productTitle;
}
//Override toString() required
#Override
public String toString() {
return productNumber + " " + productTitle;
}
// Required Product class declares abstract method with this signature: public String getDisplayText()
public abstract String getDisplayText();
//Override equals() required
#Override
public boolean equals(Object object) {
if (object instanceof Product) {
Product product2 = (Product) object;
if (productNumber == (product2.getProductNumber()) &&
productTitle.equals(product2.getProductTitle())){
return true;
}
}
return false;
}
}
Music Subclass extends Product Superclass
public class Music extends Product {
private String artist;
private String style;
private String medium;
public Music() {
super();
artist = "";
style = "";
medium = "";
}
public Music(int productNumber, String productTitle, String artist, String style, String medium) {
super();
this.artist = artist;
this.style = style;
this.medium = medium;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public String getStyle() {
return style;
}
public void setStyle(String style) {
this.style = style;
}
public String getMedium() {
return medium;
}
public void setMedium(String medium) {
this.medium = medium;
}
#Override
public String getDisplayText() {
return super.toString() + " by " + artist + " " + style + " " + medium;
}
#Override
public boolean equals(Object object){
if (object instanceof Music){
Music m = (Music) object;
if (artist.equals(m.getArtist()) &&
style.equals(m.getStyle()) &&
medium.equals(m.getMedium())){
return true;
}
}
return false;
}
}
Print String
public class Test {
public static void main(String[] args) {
// Expected result: 1234 Daughter by Pearljam Alternative online
Music music1 = new Music(1234,"Daughter", "Pearljam","Alternative","online");
System.out.println(music1.getDisplayText());
}
}
you are not passing values from subclass to your parentclass
instead of super() you need to do below -
super(productNumber,productTitle);
update needed in your code :-
public Music(int productNumber, String productTitle, String artist, String style, String medium) {
super(productNumber,productTitle);
this.artist = artist;
this.style = style;
this.medium = medium;
}
You need to pass productNumber and productTitle in the super(..., ...) call inside the Music constructor up to the parent class.
You need to invoke
super(productNumber, productTitle)
inside the Music constructor to pass the parameters to its parent.
So i have 2 classes, and in the class race i have a method ( public Athlete getAthlete(int codAthlete) ) that
should return the object corresponding to the Athlete with the code passed by parameter, but i am not sure how to
implement it. Can someone give me a hand?
public class Athlete {
private int codAthlete;
private String name;
public Athlete(int codAthlete){
this.codAthlete = codAthlete;
}
public int getCodAthlete() {
return this.codAthlete;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public String getInformation() {
return "Code: " + this.codAthlete +
" Name " + this.name;
}
}
.
public class Race {
private String idRace;
private Set<Athlete> athletes;
public Race(String idRace) {
athletes = new HashSet<>();
this.idRace = idRace;
}
public String getIdRace () {
return this.idRace;
}
public Athlete getAthlete(int codAthlete){
for(Athlete a: Athlete){
if(a.getCodAthlete() == codAthlete)
a.getInformation();
}
return (????);
// Returns the object corresponding to the Athlete with the code passed by parameter.
}
}
I have like this json.I'm using Gson to parse it and convert it in my custom class object.Here is a my java classes
public class ResponseModel {
private int resultCode;
private Match match;
public Match getMatch() {
return match;
}
public int getResultCode() {
return resultCode;
}
}
public class Match {
private Team team1;
private Team team2;
private double matchTime;
public Team getTeam1() {
return team1;
}
public Team getTeam2() {
return team2;
}
private Long matchDate;
private String stadiumAdress;
public double getMatchTime() {
return matchTime;
}
public Long getMatchDate() {
return matchDate;
}
public String getStadiumAdress() {
return stadiumAdress;
}
}
public class Team {
private String teamName;
private String teamImage;
public String getTeamName() {
return teamName;
}
public void setTeamName(String teamName) {
this.teamName = teamName;
}
public String getTeamImage() {
return teamImage;
}
public void setTeamImage(String teamImage) {
this.teamImage = teamImage;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int getBallPosition() {
return ballPosition;
}
public void setBallPosition(int ballPosition) {
this.ballPosition = ballPosition;
}
private int score;
private int ballPosition;
}
I'm using Gson like this
ResponseModel responseModel = GsonUtil.fromJson(response.toString(), ResponseModel.class);
public class GsonUtil {
public static <T> T fromJson(String json, Class<T> c) {
return new Gson().fromJson(json, c);
}
public static String toJson(Object c) {
return new Gson().toJson(c);
}
}
Everything working perfect,I can convert my json to custom class.But I want to use enum class with team1 and team2. My goal is to convert like this enum class
MatchTeamType:
TEAM1 (1);
TEAM2 (2);
How I can rewrite my code with enum class?
Thanks
I'm programming in a class and I need to have a variable from a different class. How can I do this?
package domein;
public class Speler
{
private String naam;
private String kleur;
private Sector sector;
private int Sector;
private int krediet = 10;
private int extraSchattingWaarde = 0;
private int nummer;
public Speler(String naam, String kleur, Sector sector)
{
setNaam(naam);
setKleur(kleur);
setSector(sector);
}
public String getNaam()
{
return this.naam;
}
public void setNaam(String naam)
{
//controle of het leeg is??
this.naam = naam;
}
public Sector getSector()
{
return this.sector;
}
private void setSector(Sector sector)
{
//tussen 1 en 4
this.sector = sector;
}
public String getKleur()
{
return this.kleur;
}
private void setKleur(String kleur)
{
//controle of het de beschikbare kleuren zijn
this.kleur = kleur;
}
public int getKrediet()
{
return this.krediet;
}
public void setKrediet(int krediet)
{
this.krediet = krediet;
}
public int getExtraSchattingWaarde()
{
return this.extraSchattingWaarde;
}
public void setExtraSchattingWaarde(int waarde)
{
this.extraSchattingWaarde = waarde;
}
}
This is the class where I need to get the variables and some methods. How can I make this class global?
Just a thing : this line is wrong private int Sector; because you can not use a class name as your variable name. This should hide your class visibility.
I assume this is an error and I continue the explanation.
In an other class you can instanciate this class and call the values. For example:
public class MyClass {
private Speler mySpeler = new Speler("AAA", "BBB", 3);
public MyClass() {}
public void myMethod() {
System.out.println(mySpeler.getKleur());
}
}
I get such a JSON from the server and want to parse it to my objects:
"product":{
"product_type":"assignment",
"id":717,
"product_profile":{
"title":"new Order from java",
"info":"Some special info",
"dtl_expl":true,
"special_info":""
}
}
Depend on "product_type" value I get different value of "product_profile" from server. The "product_profile" can be one of three types. I created class presentation for each of them. But question is that how organize correct parsing of JSON object to my Product class due to OOP principles? Should I create interface and implement it in each of my three classes, or I should create one parent class and extend it in my three classes to make it work right?
My classes structure. First of all Product class , object of which I should get as a result from json:
public class Product {
ProductAssignment prodAss;
ProductWriting prodWr;
ProductType returnState;
#SerializedName("id")
int id;
#SerializedName("product_type")
String product_type;
#SerializedName("product_profile")
ProductType product_profile;
public Product()
{}
public Product(int id, String product_type, ProductType product_profile)
{
this.id = id;
this.product_type = product_type;
this.product_profile = product_profile.returnObject(product_type);
}
public int getProductId()
{
return this.id;
}
public String getProductType()
{
return this.product_type;
}
public ProductType getProduct()
{
return product_profile.returnObject(product_type);
}
public void setProductId(int id)
{
this.id = id;
}
public void setProductTitle(String product_type)
{
this.product_type = product_type;
}
public void setProduct(ProductType product_profile)
{
this.product_profile = product_profile;
}
#Override
public String toString() {
return "id=" + id + " " + "title=" + product_type
+ " " + "profile=" + product_profile + "}";
}
}
Now parent class ProductType for two subclasses:
public class ProductType extends ProductType{
String product;
static ProductType productType;
static ProductAssignment productAssignment;
static ProductWriting productWriting;
IProductType component;
private ProductType returnState;
ProductAssignment prodAss;
ProductWriting prodWr;
public ProductType()
{
}
public ProductType(IProductType c)
{
component = c;
}
// implemented method of interface
#Override
public ProductType returnObject(String product_type)
{
System.out.println("ProductType");
if (product_type.equals("assignment"))
returnState = prodAss.returnObject(product_type);
else if (product_type.equals("writing"))
returnState = prodWr.returnObject(product_type);
System.out.println(returnState.getClass().getName());
return returnState;
}
}
One of the subclasses:
public class ProductWriting extends ProductType{
#SerializedName("id")
int id;
#SerializedName("title")
String title;
#SerializedName("pages_number")
int pages_number;
#SerializedName("number_of_references")
String number_of_references;
#SerializedName("dtl_expl")
boolean dtl_expl;
#SerializedName("info")
String info;
public ProductWriting()
{}
public ProductWriting(String title, String info, boolean dtl_expl,
int pages_number ,
int id,String number_of_references)
{
this.title = title;
this.info = info ;
this.dtl_expl = dtl_expl;
this.id = id;
this.pages_number = pages_number;
this.number_of_references = number_of_references;
}
public ProductWriting(IProductType c){
super(c);
}
// getters and setters
#Override
public ProductType returnObject(String res) {
System.out.println("Writing");
super.returnObject(res);
return new ProductWriting();
}
}
Another one :
public class ProductAssignment extends ProductType{
ProductAssignment thisObj;
#SerializedName("title")
String title;
#SerializedName("info")
String info;
#SerializedName("dtl_expl")
boolean dtl_expl;
#SerializedName("special_info")
String special_info;
#SerializedName("shoot_exclusive_video")
boolean shoot_exclusive_video;
#SerializedName("shoot_common_video")
boolean shoot_common_video;
public ProductAssignment()
{}
public ProductAssignment(String title, String info, boolean dtl_expl, String special_info,
boolean shoot_common_video, boolean shoot_exclusive_video)
{
this.title = title;
this.info = info ;
this.dtl_expl = dtl_expl;
this.special_info = special_info;
this.shoot_common_video = shoot_common_video;
this.shoot_exclusive_video =shoot_exclusive_video;
}
// getters and setters
#Override
public ProductType returnObject(String res) {
System.out.println("Assignment");
super.returnObject(res);
return new ProductAssignment();
}
#Override
public String toString()
{
return "title=" + title + "info " + "=" + info
+ " " + "profile=" + dtl_expl + "}";
}
}
Interface for binding my classes:
public interface IProductType
{
ProductType returnObject(String parse);
}
I tried to implement in this way, but it doesn't work for now with it.