creating an object for delegation in java - java

here is a part of code that I found while searching for delegation. I did not understand a part. Do we have to create an object for delegation? Or we can use it only with the a variable typeof the class the we want the use method of?
public class Point {
private double xCoord;
private double yCoord;
public double getXCoord(){
return xCoord;
}
public double getYCoord(){
return yCoord;
}
}
public class Circle {
/*
Is it a variable defined type of Point?
Is it possible or should it have been defined as below.
What is the difference?
*/
private Point center;
// Point center = new Point();
public double getCenterX(){
return center.getXCoord(); // Delegation
}
public double getCenterY(){
return center.getYCoord(); // Delegation
}
}

Is it a variable defined type of Point?
It's a variable, but at this point, it's not initialised (an empty variable).
Is it possible or should it have been defined as below?
You must initialise your variable (Here, create a constructor, initialise your variable and initialise the xCoord and yCoord vars.
public class Point {
private double xCoord;
private double yCoord;
public double getXCoord(){
return xCoord;
}
public double getYCoord(){
return yCoord;
}
}
public class Circle {
/*
Is it a variable defined type of Point?
Is it possible or should it have been defined as below.
What is the difference?
*/
private Point center;
// Point center = new Point();
public Circle(double x, double y) { // Constructor
center = new Point(); // Initialise variable
center.xCoord = x; // Set x
center.yCoord = y; // Set y
}
public double getCenterX(){
return center.getXCoord(); // Delegation
}
public double getCenterY(){
return center.getYCoord(); // Delegation
}
}
What is the difference?
A difference between what ?

Related

How can I access a method of a class from a generic method

I'm working on a tiny exercise java program that calculates circle and square (classes) area, that implements surface (interface) which has a method called area(). A requirement is that I have to implement a class called SumArea that has a generic method called calcArea() that receives Circle circ[] and Square square[] arrays and executes area calculation.
Program structure:
-> UseSumArea.java (main method)
-> Surface.java (interface)
-> Square.java (class that implements Surface.java)
-> Circle.java (class that implements Surface.java)
-> SumArea.java (class that executes calcArea() method)
UseSumArea.java
public class UseSumArea {
public static void main(String[] args) {
Square square[] = { new Square(2.0), new Square(5.0) };
Circle circ[] = { new Circle(3.0), new Circle(2.0) };
Surface surf[] = new Surface[square.length + circ.length];
surf[0] = square[0];
surf[1] = square[1];
surf[2] = circ[0];
surf[3] = circ[1];
SumArea sum = new SumArea();
System.out.println("Square's sum area = " + sum.calcArea(square));
System.out.println("Circle's sum area = " + sum.calcArea(circ));
System.out.println("Surface's sum area = " + sum.calcArea(surf));
}
}
Surface.java
public interface Surface {
public double area();
}
Square.java
public class Square implements Surface {
private double area;
private double side;
public Square(double l) {
this.side = l;
area();
}
#Override
public double area() {
return this.area = (this.side)*(this.side);
}
public double getArea() {
return area;
}
public void setArea(double area) {
this.area = area;
}
public double getSide() {
return side;
}
public void setSide(double side) {
this.side = side;
}
}
Circle.java
public class Circle implements Surface {
private double area;
private double radius;
public Circle (double r) {
this.radius = r;
area();
}
#Override
public double area() {
return area = (((this.radius)*(this.radius))*(Math.PI));
}
public double getRadius() {
return radius;
}
public void setRadius(double raio) {
this.raio = raio;
}
public double getArea() {
return area;
}
public void setArea(double area) {
this.area = area;
}
}
SumArea.java
public class SumArea {
private double area;
public <T> double calcArea(T[] t) { //generic method that receives Square and Circle arrays
double arrayArea = 0;
for (T a : t) {
arrayArea = arrayArea+(a.area());
}
return this.area = arrayArea;
}
}
My doubt is over this SumArea's code snippet:
arrayArea= arrayArea+(a.area());
How can I access the area() method of each Circle and Square objects inside this generic method?
You need to bound the type variable:
public <T extends Surface> double calcArea(T[] t) {
or just declare the parameter as an array of Surfaces:
public double calcArea(Surface[] t) {
Note that the latter is preferable because generics and arrays don't play very nicely together. If you were to need to have a type variable for other reasons, it would be advisable to change to a Collection, or similar:
public <T extends Surface> double calcArea(Collection<T> t) {
(And, as a minor matter of preference, I would use S rather than T to name a type variable which extends Surface)
Since the problem in regard to generic types is already addressed by Andy Turner, I just want to add a suggestion related to the class design.
I think there is a bit of redundancy in how these classes were designed. You need to create an instance of SumArea in order to do the calculation. And the result of the last of the last calcArea() method call will be stored in this object (let's assume that this calculation is far more complex and CPU-consuming).
But do we really need to store somewhere else the value is already returned by the method? In this case, the idea to cash the history of calculations (as a single variable or as a collection of values) doesn't seem to be useful because it can't be reused without knowing which objects were involved in the calculation.
And without storing the result this method will not be bound to a state, i.e. it has to be static. And since interfaces can have static methods, instead of creating a utility class for that purpose it could be placed in the Surface interface. Like that.
public interface Surface {
public double area();
public static <T extends Surface> double calcArea(T[] t) { // generic method that receives Square and Circle arrays
double arrayArea = 0;
for (T a : t) {
arrayArea += a.area();
}
return arrayArea;
}
}
Note that static behavior declared in interfaces in contrast to classes could be invoked only by using the name of an interface:
System.out.println("Circle's sum area = " + Surface.calcArea(circ));
Also note that it makes sense for both classes to have a field area inside the classes Circle and Square only if other fields will be declared as final, i.e. they must be initialed only one during the object construction and setters become unnecessary.
In this case (assuming that radius has been declared as final and is being validated when assigned so that reduce > 0) method area() will look like this:
#Override
public double area() {
if (area > 0) { // `0` is a default value for instance variables
return area; // reusing already calculated value
}
return area = radius * radius * Math.PI;
}
And there mustn't be two methods area() and getArea() leave either one or another.

How should I pass the "type" parameter of in a single constructor in an if/else statement?

How should I pass the "type" parameter of a constructor in an if/else statement? For eg - cal(2,2,0,rectangle). So if the type=rectangle then calculate area of a rectangle. If type=circle, calculate the area of a circle.
I am using a single constructor. My issue is that I know the logic but I can't write it in syntax. I am using Java or Apex.
I want to use if-else statement. How should I pass the type parameter in the code?
My program is like this -
if "type"=square, the compiler will call calculate area of the square.
if "type"=circle, the compiler will call calculate area of the circle.
public class Area {
private String type;
private Integer length;
private Integer breadth;
private Integer height;
private Integer area;
public void setType(String t){
type=t;
}
public void setLength(Integer l){
length=l;
}
public void setbreadth(Integer b){
breadth=b;
}
public void setheight(Integer h){
height=h;
}
/* public void setArea(Integer a){
area=a;
} */
public Integer getLength(){
return length;
}
public Integer getbreadth(){
return breadth;
}
public Integer getheight(){
return height;
}
public string gettype(){
return type;
}
public Integer AreaRectangle(){
return area=length*breadth;
}
public Integer AreaSquare(){
return area=length*length;
}
public integer AreaTriangle(){
return area=1/2 *(breadth*height);
}
public Area(){ // default constructor
length=9;
breadth=2;
height=7;
}
public Area(String t,Integer l ,Integer b,Integer h ){ // parameterised constructor
type=t;
length=l;
breadth=b;
height=h;
}
}
You don't. You create an abstract class called shape.
public abstract class Shape {
abstract double area();
}
And then two other classes that extend Shape and each provides the proper implementation
public class Square extends Shape {
private int side;
public Square(int side) {
this.side = side;
}
public double area() {
return (double) side * side;
}
}
Now at the place you want to call it:
Shape shape = new Square(5);
double area = shape.area();
Int radius = 4;
shape = new Circle(radius);
double circle area = shape.area();

How to get the known values of variables I store in a Java Object?

I read a JSON and stored data into different objects. I stored some coordinates in a class named Geometry. The class looks like this:
public class Geometry {
private Object[] coordinates;
private String type;
public Object[] getCoordinates() {
return coordinates;
}
}
As you can see, coordinates field is an array of class Object.
Knowing that coordinates will always have 2 positions (2 coordinates) and that the type of those coordinates is double, how can I get the double value of the coordinates?
To be more exact, what do I have to write on the following method for the system to return the two coordinates explicitly?
public double[] returnCoordinates() {
double[] coord;
coord[0] = //?
coord[1] = //?
return coord;
}
One solution would be to store an array, or even a Collection, of Coordinate objects inside of the Geometry object. If you're not already using Gson look into it, it will make life very easy.
class Coordinate {
private final double x;
private final double y;
public Coordinate(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
}
public class Geometry {
private final Collection<Coordinate> coordinates;
private final String type;
public Geometry(Collection<Coordinate> coordinates, String type) {
this.coordinates = coordinates;
this.type = type;
}
public Collection<Coordinate> getCoordinates() {
return coordinates;
}
}

How to make a singleton reinitialize variables?

My singleton class:
public class XandY {
private double x, y;
private static XandY xy;
//Constructor sets an x and y location
private XandY() {
x = 210.0;
y = 100.0;
}
public static XandY getXandY() {
if (xy == null)
xy = new XandY();
return xy;
}
public void updateXandY() {
x += 10;
y += 5;
}
}
Other class that changes singleton values and tries to reinitialize. My question is if I call changeXandY a few times then want to call resetXandY how do I make it reset back to the original x and y?
public class GameWorld {
private List<GameObject> objects;
public void initialize() {
objects = new ArrayList<GameObject>();
objects.add(XandY.getXandY());
...add other objects that are not singletons
}
public void changeXandY {
for (int i=0; i<gameObject.size(); i++) {
if (gameObject.get(i) instanceof XandY)
((XandY)gameObject.get(i)).updateXandY();
}
public void resetXandY {
initialize();
}
}
For this use case, you could simply store them as default values. Such as
private double x, y;
private static XandY xy;
private static final double default_x = 210.0;
private static final double default_y = 100.0;
That way when you reset, just:
public void resetXandY {
this.x = default_x;
this.y = default_y;
}
That being said, you may want to change your default constructor to look the same way.
If you can make the XandY reference protected, you can use a static initializer in an anonymous subclass:
// I need to reset the singleton!
new XandY(){
{ xy = null; }
};
But really, if you need to be able to (re)initialize the singleton, you should put a method to that effect into its signature. Obscure solutions are, at best, still obscure...
Create a resetXandY() method to set default value:
public class XandY {
private double x, y;
private static XandY xy;
//Constructor sets an x and y location
private XandY() {
x = 210.0;
y = 100.0;
}
//reset x=0 and y=0
public void resetXandY() {
x = 0;
y = 0;
}
public static XandY getXandY() {
if (xy == null)
xy = new XandY();
return xy;
}
public void updateXandY() {
x += 10;
y += 5;
}
}

Pass variables into other classes or have variables be used by different classes

Image of Description
The aim is to have the user select a shape (Square, Triangle or Circle) and then enter a boundary length. Once this information has been input I can then calculate the perimeter and area of their choice.
The problem is I don't want to create new variables for the length and area in each class if I don't have to and would rather have the variables declared and then passed into the classes if I can.
Basically I don't want to do it like this,
class square {
double bLength;
double area;
}
class triangle {
double bLength;
double area;
}
class circle {
double bLength;
double area;
}
Can I declare them outside of the classes and then have the classes use/inherit them or anything?
I must apologise for such a basic question, I am quite new to Java and I can't really think around this one.
The classic solution is to use inheritance:
class Shape {
double bLength;
double area;
Shape(double bLength, double area) {
this.bLength = bLength;
this.area = area;
}
}
class Square extends Shape {
Square(double bLength, double area) {
super(bLength, area);
}
// additional field, methods...
}
// same for the other shapes
You can use inheritance for this problem in following way :
Declare a class called Shape from which all other classes would inherit
public class Shape {
public double length = 0;
public abstract double GetPerimeter();
public abstract double GetArea();
public Shape(double length) {
this.length = length;
}
}
Then have your specialized classes. E.g. :
public class Circle extends Shape {
public Circle(double length) {
super(length);
}
public double GetPerimeter() {
// Implement the perimeter logic here
}
public double GetArea() {
// Implement the area logic here
}
}
Do this for all classes. This way you have the variable in only one class, and all others inherit from it.
EDIT
If you want even further optimization (for instance, you don't want function call overhead), something like perhaps
public class Shape {
public double length = 0;
public double perimeter= 0;
public double area= 0;
public Shape(double length, double perimeter, double area) {
this.length = length;
this.perimeter= perimeter;
this.area = area;
}
}
public class Circle extends Shape {
public Circle(double length) {
super(length, 2 * Math.PI * length, Math.PI * length * length);
}
}

Categories

Resources