When to use nested class [duplicate] - java

This question already has answers here:
When to use nested class?
(3 answers)
Closed 9 years ago.
If a function returns 2 values, for example: min/max in array or for example, x and y axis of a point, it would need to create an object, since a function cannot return 2 values.
Now, consider a client whose 'only' function is to use getters in the returned object and print.
AND
The returned object say MinMax or Point object is created only by one class,
Should we use a nested class (eg: MinMax, Point can be nested class) or use a top level class?
This is a generic question - below is just one such example related to the question. Please done answer related to the code sample as it is a very generic question not bound to the sample code.
Should the Point class be inner class returned similar to the way itr is returned by arraylist ?
class Point {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
int getX() {
return x;
}
int getY() {
return y;
}
}
public class IntersectionOf2Lines {
public static Point calculateIntersection(Line line1, Line line2) {
int x = (line2.getConstant() - line1.getConstant()) / (line1.getSlope() - line2.getSlope());
int y = line1.getSlope() * x + line1.getConstant();
return new Point(x, y);
}
Line line3 = new Line(2, 2);
Line line4 = new Line(3, 2);
Point p1 = IntersectionOf2Lines.calculateIntersection(line3, line4);
System.out.println("Expected: x = 0, Actual x = " + p1.getX() + " Expected y=2, Actual y = " + p1.getY());

IMHO it is a matter of style. I would look at it from the point of view of someone who is reading your code from the first time. Which classes do you want to make obvious and which ones do you want to group away and they only need to read when they get into the details.
BTW: A nested class need to be nested inside the scope of another class, not just in the same class file as it is in your example.

Related

Java questions this and arguments for constructor

I am very new with Java and now read book Shield complete reference 9th edition.
I wrote the next code:
class Area {
double Area (double x, double y){
double z;
this.z = 5; // Problem 1
return z = x*y;
};
}
class ThisIsSparta {
public static void main (String args []){
double x = 10;
double y = 5;
double z = 0;
Area result = new Area (x,y); //Problem 2
z = result.Area(x, y);
System.out.println("Test " + z);
}
}
Problem 1: I could not understand purpose of "this", I thought that it is reference to object which had call class. So in my opinion I should return to main with z = 5. Instead i'am getting an error (compiler does not pass through it).
Problem 2: In a book example constructor was called with two arguments right during declaration, but in my case compiler do not allow to do it. Yes, I could do it in the next line, but I don't understand what is wrong.
Problem 1 :
this refers to the current object. In your case, it is an object of Area.
Read more:
What is the meaning of "this" in Java?
Problem 2:
You have not defined any constructor that takes two argument.
double Area (double x, double y) is not the right signature for a constructor as it contains return type as double.
Read more on this here : Why do constructors not return values?

Basics to creating a class in java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
This is a simple question, but my AP Comp Sci book just doesn't explain it well enough and you guys are always useful.
What is the basic way of creating a custom class in Java and creating methods within that class, then later calling those methods. I know its simple but I can't find a good explanation anywhere
It seems like you need a better understanding of OOP. So, let's create a class and a test client to help you. We will create a class and a test client (or driver) to compute electrical potential. Please note this example is from Introduction to Programming in Java by Robert Sedgewick and Kevin Wayne (an excellent book I highly recommend).
First we create a Charge class:
/*
Separate classes must be in the same directory as main method or must invoke
classpath
*/
public class Charge {
// first declare instance variables which are usually private
private final double rx;
private final double ry;
private final double q;
/* A class contains constructors that are invoked to create objects from a
class blueprint. Constructor declarations look like method declarations
-except that they use the name of the class and have no return type.
Constructors must use the exact name of the class, case sensitive.
Classes and Constructors are capitalized - methods are camelCase.
*/
// Constructor
public Charge(double x0, double y0, double q0) {
rx = x0;
ry = y0;
q = q0;
}
/*
The method to compute electrical potential which is defined by the equation
V = kq/r
*/
public double potentialAt(double x, double y) {
double k = 8.99e09; // Electrostatic Constant that k=8.99 X 10^9 Nm^2/C^2 (N = Newtons, m = meters, C = Coloumbs)
// r = delta x - delta y
double dx = x - rx; // delta x for distance
double dy = y - ry; // delta y for distance
return k*q/Math.sqrt(dx*dx + dy*dy); // Computation using distance formula
}
}
This would be the API to use this class. An important concept in Java programming
is that you do not need to know how a data type is implemented to be able to use it.
public class Charge
This is the constructor:
Charge(double x0, double y0, double q0)
These are instance methods. The most important difference between a variable of
reference type vs primitive type is that you can use reference type variables
to invoke methods that implement data type operations.
double potentialAt(double x, double y)
String toString()
The two parts of using this class would be:
1. Create an object
ClassName object = new ClassName (invoke Constructor)
--------- ------ --- --------- -----------------
Charge c = new Charge (2.2, 3.4, 7.2)
2. Use instance methods on object
c.potentialAt(2.3, 4.2)
This would be the client (or driver) that could be used with this class:
import java.util.*;
public class ChargeClient {
public static void main(String[] args) {
// Using a scanner object to get values
System.out.println("Please enter an X Value");
Scanner in = new Scanner(System.in);
double x = in.nextDouble();
System.out.println("Please enter a Y Value");
double y = in.nextDouble();
/*
1. Instantiate objects c1 and c2
ClassName object = new ClassName (invoke Constructor)
--------- ------ --- --------- -----------------
Charge c = new Charge (2.2, 3.4, 7.2)
2. We are invoking constructor from API
Charge(double x0, double y0, double q0)
*/
Charge c1 = new Charge(.51, .63, 21.3);
Charge c2 = new Charge(.13, .94, 81.9);
// print out charge so we know what we are dealing with
System.out.println(c1);
System.out.println(c2);
/*
Here we create variables to hold the return from our potential method
which is enacted on our c1 and c2 objects.
1. We call a method on an object by:
objectName.methodName(appropriate parameters)
*/
double v1 = c1.potentialAt(x, y);
double v2 = c2.potentialAt(x, y);
// Concatenate results and print them out.
System.out.println(v1 + v2);
System.out.println("This is the printf statement:");
System.out.printf("%.2E\n", v1 + v2);
}
}

Design choice for two almost identical classes

I have two classes Boat and Mines, which have exactly the same methods and variables.
the only difference is that they are Initialized in different positions.
for Boat
xPosition = 3
yPosition = 4
for Mine
xPosition = 1
yPosition = 1
I've been told specifically not to use inheritance for this, what else could I use to improve the design
You could give both of them some sort of location class, give that class the X and Y positions, and make it a property of both the mine and the boat. Sad thing you'll need getters/setters for the location class nevertheless.
The idea of object-oriented programming is for this exact reason.
Boat and Mine should not be classes, they should be new objects made from another class (we'll call it - waterStuff).
class waterStuff {
public xPosition;
public yPosition;
}
... then somewhere in the code you set them to new objects. I don't use Java so I'll do it as close as I can:
(these would probably be inside another class using the waterStuff as a namespace for reference)
Boat = new waterStuff;
Mine = new waterStuff;
Boat->xPosition = 3;
Boat->yPosition = 4;
Mine->xPosition = 1;
Mine->yPosition = 1;
I wish I could be more java-specific but hopefully this gets you on the right track.
EDIT: Don't you just love CS101
If they only differ in the values of their members, inheritance seems somewhat pointless in any case. But having 2 unrelated classes would be worse.
How about something like this?
class SomeClass
{
int xPosition, yPosition;
enum Type
{
Boat, Mine
}
public SomeClass(Type type)
{
if (type == Type.Boat)
{
xPosition = 3;
yPosition = 4;
}
else
{
xPosition = 1;
yPosition = 1;
}
// assign 'type' to a class variable here if required
}
}
Construct using:
new SomeClass(SomeClass.Type.Boat)
or:
new SomeClass(SomeClass.Type.Mine)
You may want to pick a better name than SomeClass.

Accessor: cannot find symbol error. [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm fairly new to java, so bear with me.
I'm using x and y variables inside a coordinate array.
Mutator:
public void setCoordinate (double _x, double _y) {
x = _x;
y = _y;
double [] coordinate = new double [2];
coordinate[0] = x;
coordinate[1] = y;
}
The part I'm having trouble with is the accessor:
public double[] getCoordinate() {
return "(" + coordinate[0] + ", " + coordinate[1] + ")";
}
I'm getting a "symbol: variable coordinate, location: class Address, error: cannot find symbol" error. Any idea as to why I'm getting this error? I wrote the other accessors the same way and I'm not having any trouble.
Also... how would I call each variable (x and y) separately in another method? a1.getCoordinate() returns both values (x, y), but I want to use x and y in an equation later on an I'm not 100% sure of how to do this.
Your first problem is due to the coordinate variable being declared inside of the setCoordinate(...) method, and thus it is visible only in this method and invisible everywhere else. In other words, its scope is limited to the method.
One solution to this problem is to make coordinate a class field, but if you do this, then you will want to get rid of the x and y class fields since they will be unnecessary duplicate variables and can lead to confusion if x and y somehow get out of sync with coordinate. i.e.,
private double[] coordinate;
public void setCoordinate(double x, double y) {
coordinate = new double[]{x, y}; // coordinate is a class field
}
public double[] getCoordinate() {
coordinate;
}
Alternatively you can keep x and y and simply create a double array object on the fly inside of the getCoordinate() method with your x and y variables as the need arises. i.e.,
private double x;
private double y;
public void setCoordinate(double x, double y) {
this.x = x; // x is a class field
this.y = y; // y is a class field
}
public double[] getCoordinate() {
return new double[] {x, y};
}
Your second problem is that the getCoordinate() methods declares that it will return a double array:
public double[] getCoordinate() {
but you're trying to return a String:
return "(" + coordinate[0] + ", " + coordinate[1] + ")";
You don't want to do this since it "breaks the method's contract", since you're not returning the type you've promised to return. Instead return the type that the method has been declared to return (or a child type of the declared type since return types allow for "covariance" -- but this is not applicable in your situation).
double [] coordinate = new double [2];
should be declared outside the mutator as its scope is only for that mutator.
You should have something as follows:
class SomeClass{
double [] coordinate = new double [2];
int x, y;
public double[] getCoordinate;
//methods
}
You're defining coordinate in the scope of the setCoordinate function. You'll need to define coordinate at the class level in order to access it in both methods.

Making java wait until a property is called for?

I recently started working with JOGL, so I made a vector class. Inside this class, I used the line
public Vector unit=new Vector(x/length,y/length,z/length);
To find the unit vector. And of course, this causes a stackoverflow. Is there any way to make java wait for unit to be called before running this or will I have to make unit a method?
I woukld personally create a second constructor, which calculates the unit vector and sets its own unit vector to itself. You should ideally use private values and a get method as Ernest suggests. The reason for this is that otherwise other classes can simply overwrite the x,y,z, etc. values if they have access to one of your objects. Java has a tradition of using final classes for pure data storage. See the String class for example. You can't modify an existing String, only create a new String. Once created, a String remains the same. For your purposes it might not matter much, but in a different context it may cause your application to misbehave, if your class is used by someone who doesn't have a clue. It might even be a security risk in some cases.
You could simply ignore this and access the variables directly, and enjoy the less cluttered code and small performance increase. But I would still suggest knowing what the problem is for the future.
Anyway, below is my suggested code for solving the unit vector problem, minus getter methods.
import java.lang.Math;
class Vector{
public double x,y,z,length;
public Vector unit;
public static void main(String[]s){
new Vector(5,5,5);
}
public Vector(double x, double y, double z){
this.length = Math.sqrt(x*x + y*y + z*z);
this.x=x;
this.y=y;
this.z=z;
this.unit = new Vector(x/length, y/length, z/length, true);
}
private Vector(double x, double y, double z, boolean isUnitVector){
// Temp variable for calculating the length
double length = Math.sqrt(x*x + y*y + z*z);
if (isUnitVector){
this.length = 1;
this.x=x/length;
this.y=y/length;
this.z=z/length;
this.unit = this;
}else{
this.length = Math.sqrt(x*x + y*y + z*z);
this.x=x;
this.y=y;
this.z=z;
this.unit = new Vector(x/length, y/length, z/length, true);
}
}
}
I'm not entirely happy with the code duplication between the constructors that follows from the boolean argument. In practice, I would probably create a factory class, VectorFactory with one static method, whose only job is to create Vector objects. Or maybe just use Java's own javax.vecmath.Vector3d and related classes.
Yes, this is easy enough, but you'll need to fix your design a bit. Most importantly, as is almost always the case with all member variables, unit should be private, and all access to it should be through a method named something like getUnit(). Then, you simply write getUnit() to check whether unit has been initialized or not:
public synchronized Vector getUnit() {
if (unit == null)
unit = new Vector(x/length,y/length,z/length);
return unit;
}
I've made this method synchronized so that you'll avoid any problems if two different threads call getUnit() at around the same time, and unit hasn't been initialized yet.
I propose a constructor which decides itself whether it is a unit vector or not. If it is a unit vector, then unit points to itself. This will break the recursion of the constructor.
The only problem might be numbers where length is not exactly 1.0 due to rounding errors.
public class Vector {
public double x, y, z;
public Vector unit;
public Vector(double x, double y, double z){
this.x = x;
this.y = y;
this.z = z;
double length = calcLength(x, y, z);
if( length == 1.0 ) // perhaps add a little fuzz factor.
this.unit = this;
else
this.unit = new Vector(x/length, y/length, z/length);
}
}

Categories

Resources