Get reference of the object from a separate class - java

Currently, there are 3 classes which are not inheriting to each other. Each class has a property in it that references to an instance of another class as below.
import java.util.ArrayList;
class Region {
private Directory areaDirectory;
public Region() {
areaDirectory = new Directory();
}
public Directory getAreaDirectory() {
return areaDirectory;
}
public void setAreaDirectory(Directory areaDirectory) {
this.areaDirectory = areaDirectory;
}
}
class Directory {
private ArrayList<Area> areaList;
public Directory() {
areaList = new ArrayList<>();
}
public ArrayList<Area> getAreaList() {
return areaList;
}
public void setAreaList(ArrayList<Area> areaList) {
this.areaList = areaList;
}
public Area addNewArea(){
Area area = new Area();
return area;
}
}
class Area {
private String Name;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public Region getAreaRegion() {
// This returns a new region but need the region it was created in
return new Region();
}
}
public class Scratch {
public static void main(String args[]) {
Region r = new Region();
Area a = r.getAreaDirectory().addNewArea();
a.setName("Demo");
//See getAreaRegion() method in Area class
System.out.println(a.getAreaRegion());
}
}
How to implement a method like getAreaRegion() such that it returns the region object r? How to setup inheritance in this example to get parent objects?

I have understood the business logic which you want to describe with codes as below:
There is a region. Every region has a directory. And every directory has an area.
In this case I think it would be nice if :
Region class holds reference to Directory field;
And Directory class also has reference for its own Region;
Directory class holds reference to Area field;
And Area class also has reference for its own Directory.
Then we can create classes in following way:
1.Region class
public class Region {
private Directory directory;
public Directory getDirectory() {
return directory;
}
public void setDirectory(Directory directory) {
this.directory = directory;
}
}
2.Directory class
class Directory{
private Region region;
private Area area;
public Region getRegion() {
return region;
}
public void setRegion(Region region) {
this.region = region;
}
public Area getArea() {
return area;
}
public void setArea(Area area) {
this.area = area;
}
}
3.Area class
class Area{
private Directory directory;
private String Name;
public Directory getDirectory() {
return directory;
}
public void setDirectory(Directory directory) {
this.directory = directory;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
}
So we can get region of area as following:
area.getDirectory().getRegion();
I think this shows business logic better and simply. Hope it would be helpful for someone:)

Related

how to create a List type of non public class from another package?

My Package A has one java file with 2 classes. Login class which is public and LoginDetails class which cannot be public because it is in the same file. how to create a List of LoginDetails type from Package B.
package A;
public class Login {
private String name;
private String passWord;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
#Override
public String toString() {
return "Login [name=" + name + ", passWord=" + passWord + "]";
}
}
class LoginDetails{
public LoginDetails(int id, int geight) {
super();
this.id = id;
this.geight = geight;
}
private int id;
private int geight;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getGeight() {
return geight;
}
public void setGeight(int geight) {
this.geight = geight;
}
public void hidden() {
System.out.println("From hidden");
}
public LoginDetails() {
}
}
package B;
import java.util.ArrayList;
import java.util.List;
public class Demo {
public static void main(String[] args) throws Exception {
List<LoginDetails> l = new ArrayList<LoginDetails>();
}
}
A solution to your weird question which doesnt include changing neither of the Login nor LoginDetails classes would be by adding a second Public class called AUtils such like this:
AUtils/AFactory class
package A;
import java.util.ArrayList;
public class AUtils {
public static ArrayList<LoginDetails> generateList(){
return new ArrayList<LoginDetails>();
}
public static ArrayList<LoginDetails> generateListWithInitialSize(int x){
return new ArrayList<LoginDetails>(x);
}
public static LoginDetails generateAnObject(){
return new LoginDetails();
}
public static LoginDetails generateWithData(int id, int geight){
return new LoginDetails(id,geight);
}
}
And your Demo would look like this:
public class Demo {
public static void main(String[] args) {//plus you dont need To throw exception thus your program dont throw any!:)
List l = AUtils.generateList();
// List l = AUtils.generateListWithInitialSize(10);//will give you array list with initial size 10
l.add(AUtils.generateAnObject());//if you do so be aware that the objects would be created with 0 as id and eight.
// l.add(AUtils.generateWithData(3,3));
}
}
please be aware that this normally is not acceptable and considered as bad coding because its kinda turn around ;) so either you misunderstood the assignment or the one who wrote it is really a carrot.
happy coding.
You cannot do it directly without changing of the design or visibility of the classes.
If a class has no modifier (the default, also known as
package-private), it is visible only within its own package.
https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

How to serialize with Gson an object that defines variable with same name as variable inherited from parent

I want to write a new class that extends another, and in the new class I want to define a variable with the same name as one in the parent. I can do this fine in Java since both are private but when I try to serialize the object with gson I get an error since there are two properties with the same name (even if the one inherited from the parent class is null and therefore should not be included in the json).
For example consider these classes:
public class Car {
private String color;
private Seat seat;
}
public class Seat {
private boolean isAdjustable;
}
and these classes:
public class FancyCar extends Car {
private FancySeat seat;
private boolean hasSpoiler;
}
public class Fancyseat extends Seat {
private boolean hasSeatWarmers;
}
with these classes I could create a new FancyCar with a seat that isAdjustable and hasSeatWarmers. But if I were to serialize with gson it would throw an exception as it tries to parse both the variables named seat even if the one inherited from Car is null.
Is there a better way to design these classes? Or a way to tell gson to ignore null fields altogether?
You can use #SerializedName(value = "fancySeat") Also, from Gson version.2.4 There is an option to alternate or have multiple name for serializedName when deserializing. No Need of CustomTypeadapter.
Gson Field Naming
Example for Multiple deserialization names
package com.test.practice;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
public class JsonSerializationExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
Seat seatCar = new Seat();
seatCar.setAdjustable(true);
Fancyseat fancySeat = new Fancyseat();
fancySeat.setHasSeatWarmers(true);
fancySeat.setAdjustable(false);
Car car = new Car();
car.setColor("black");
car.setSeat(seatCar);
FancyCar fancyCar = new FancyCar();
fancyCar.setColor("white");
fancyCar.setSeat(fancySeat);
Gson gson = new Gson();
String jsonString = gson.toJson(fancyCar);
System.out.println("json :: "+jsonString);
}
}
class Car {
private String color;
private Seat seat;
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public Seat getSeat() {
return seat;
}
public void setSeat(Seat seat) {
this.seat = seat;
}
}
class Seat {
private boolean isAdjustable;
public boolean isAdjustable() {
return isAdjustable;
}
public void setAdjustable(boolean isAdjustable) {
this.isAdjustable = isAdjustable;
}
}
class FancyCar extends Car {
#SerializedName(value = "fancySeat")
private Fancyseat seat;
private boolean hasSpoiler;
public Fancyseat getSeat() {
return seat;
}
public void setSeat(Fancyseat seat) {
this.seat = seat;
}
public boolean isHasSpoiler() {
return hasSpoiler;
}
public void setHasSpoiler(boolean hasSpoiler) {
this.hasSpoiler = hasSpoiler;
}
}
class Fancyseat extends Seat {
private boolean hasSeatWarmers;
public boolean isHasSeatWarmers() {
return hasSeatWarmers;
}
public void setHasSeatWarmers(boolean hasSeatWarmers) {
this.hasSeatWarmers = hasSeatWarmers;
}
}

Make list of non public class

I have a java file in which I have two classes in which one is public and another is default like this -
import java.util.List;
public class TaskAnswers {
private float ratings;
private List<Image> imageList;
public float getRatings() {
return ratings;
}
public void setRatings(float ratings) {
this.ratings = ratings;
}
public List<Image> getImageList() {
return imageList;
}
public void setImageList(List<Image> imageList) {
this.imageList = imageList;
}
}
class Image {
private String image;
private String caption;
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
}
I want to make a list of Image class type in another class. And when we write like this than that java file is called as what?
Java only allows one public class per source file. Try making the Image class public and you will get compiler errors. You need to call the file TaskAnswers.java since it is a requirement that the name of the source file match the name of the public class contained in that file.
As user #NwDx mentioned the Image class is package protected, which means you will only be able to instantiate it from other Java classes that share the same package. If you need to access the Image class in a separate package, it would be a better design choice to move it into its own public class file rather than making it an inner class.
And the code example you posted in your original problem looks just fine.
If you need the class Image in other packages, you have to make it public, but in this case you need to move it to an inner class of TaskAnswers or make an own class (file).
public class TaskAnswers {
private float ratings;
private List<Image> imageList;
public float getRatings() {
return ratings;
}
public void setRatings(float ratings) {
this.ratings = ratings;
}
public List<Image> getImageList() {
return imageList;
}
public void setImageList(List<Image> imageList) {
this.imageList = imageList;
}
public static class Image {
private String image;
private String caption;
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
}
}
For more information please look in the Java Nested Classes Tutorial
Image class is called as utility class and TaskAnswers is called as functionality implementation class you can use it in following manner and you are using the concept of high cohesion
List<Image> list = new ArrayList<Image>();

Java Encapsulation Constructor Method

Hi all I am working on a java code for student health. what I am trying do is
A) Make a constructor method that initializes only the first 2 data fields
(name and date-of-birth). Also, increment the patient counter data field.
B) Secondly make a constructor method that initializes all the data fields. Also, increment the patient counter data field.
If I recall correctly in order to make a constructor method that initializes the first two variables (in this case name and DOB) it goes something like this.
public emr (String name, Long dob){
However when I put that in my emr class my main method comes up with errors saying "constructor emr class cannot be applied to given types"
In my main Method I have
package studenthealthservices;
public class Studenthealthservices {
public static void main(String[] args) {
emr p1 = new emr();
p1.setName("Colin");
emr p2 = new emr();
p2.setName("Anquan");
emr p3 = new emr();
p3.setName("Buster");
emr p4 = new emr();
p4.setName("Hunter");
emr p5 = new emr();
p5.setName("Nori");
}
}
This is my emr class code
package studenthealthservices;
public class emr {
private String name;
private Long dob;
private String rfv;
private double bodyt;
private double hr;
private String diag;
private String pmeds;
public void setName(String name) {
this.name = name;
}
public Long getDob() {
return dob;
}
public void setDob(Long dob) {
this.dob = dob;
}
public String getRfv() {
return rfv;
}
public void setRfv(String rfv) {
this.rfv = rfv;
}
public double getBodyt() {
return bodyt;
}
public void setBodyt(double bodyt) {
this.bodyt = bodyt;
}
public double getHr() {
return hr;
}
public void setHr(double hr) {
this.hr = hr;
}
public String getDiag() {
return diag;
}
public void setDiag(String diag) {
this.diag = diag;
}
public String getPmeds() {
return pmeds;
}
public void setPmeds(String pmeds) {
this.pmeds = pmeds;
}
}
If you do not write a constructor, a public constructor with no arguments is created by default.
This default constructor is the constructor you are using in main when you write new emr().
However, when you write your own constructor, then the default constructor will not be created, so main will no longer compile. If you want main to continue to compile even after you have written the new constructor, you will have to also write a second constructor with no arguments.

java Composite design pattern(Directory &File)

The outputs below are different. I don't know what's wrong and I have tried to correct many times.
There has File and Folder two java files.And for the format, for a listed folder,there must be a "/" at the end and for each folder/file, the path must be the absolute path.
The output must be
dir1/
dir1/f1/
dir1/dir2/
dir1/dir2/f3/
dir1/dir2/f4/
dir1/dir2/dir3/
dir1/dir2/dir3/f5/
dir1/f2/
However,my output is
dir1/
dir1/f1/
dir1/dir2/
dir2/f3/
dir2/f4/
dir2/dir3/
dir3/f5/
dir1/f2/
Here is my code.
public class File implements Composite {
public String name;
//private ArrayList<File>a=new ArrayList<File>();
public File(String name)
{
this.name=name;
}
public void list() {
System.out.print(name+"/");
System.out.println();
}
}
Folder.java
import java.util.ArrayList;
public class Folder implements Composite{
public String name;
public ArrayList b = new ArrayList();
public Folder(String name){
this.name=name;
}
public void add(Object o)
{
b.add(o);
}
public void list(){
int e=b.indexOf(name)+1;
System.out.println(name+"/");
Composite r=(Composite) b.get(e);
for(int i=0;i<b.size();i++) {
System.out.print(name+"/");
Composite a=(Composite)b.get(i);
a.list();
}
}
public String getName(){
return name;
}
}
In your code, you need to track the parent folder of each Folder.
So the constructor needs to be Folder(Folder parent, String name). The root (topmost) folder has null as parent.
When you print the name, you need to ask the current folder for it's path. The code for this method would be:
public String getPath() {
if(null == parent) return name;
return parent.getPath() + "/" + name;
}

Categories

Resources