I am learning java and trying to execute a simple script. I have a class Point as the following:
package user_package;
public class Point {
float x;
float y;
float z;
public Point(float x, float y, float z){
this.x = x;
this.y = y;
this.z = z;
}
public static Point add(Point p1, Point p2){
return new Point(p1.x + p2.x, p1.y + p2.y, p1.z + p2.z);
}
}
Then I have the main file like this:
import user_package.Point;
import static user_package.Point.add;
class Tutorial{
public static void main(String[] args){
float x1 = 1, y1 = 1, z1 = 1;
float x2 = 2, y2 = 2, z2 = 2;
Point p1 = new Point(x1, y1, z1);
Point p2 = new Point(x2, y2, z2);
Point p3 = add(p1, p2);
System.out.println(p3);
}
}
I do this in Netbeans. It gives me no errors and the build is successful but the output is:
user_package.Point#68e26d2e
I tried to search myself but nothing found. Please tell me what the problem is and how I can solve it.
You have not overridden toString method for Point class so the Object class toString method is called. If you want meaningful textual representation of your object, override toString
public String toString(){
return "stringYouWantToReturn";
}
In your case, add this to Point class
public String toString() {
return "Point [x=" + x + ", y=" + y + ", z=" + z + "]";
}
When you print an object using println method, toString() is implicitly called.
When you write
System.out.println(p3);
There toString() calls on the Object you passed.
Since you didn't provide any implementation there,
You have to ovveride the toString() method in your Point class.
As per docs of toString()
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object.
So
user_package.Point#68e26d2e is the textual representation of Point class.
To get the required output, write the logic in overridden toString method in Object class and return the string there.
package user_package;
public class Point {
float x;
float y;
float z;
public Point(float x, float y, float z){
this.x = x;
this.y = y;
this.z = z;
}
public static Point add(Point p1, Point p2){
return new Point(p1.x + p2.x, p1.y + p2.y, p1.z + p2.z);
}
#Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append(this.x).append(",");
result.append(this.y).append(",");
result.append(this.z)
return result.toString();
}
}
You're printing object of class Point. If println() method doesn't know how to print a class, it prints its name. That's why you get such result.
You can do it either like this:
System.out.println(p3.x + ", " + p3.y + ", " + p3.z);
Or as SURESH ATTA suggested, by overriding toString() method for your Point class (or in other words - learning your Point class to know how to behave when you want to print it).
You need to override toString() function in Point class or create user defined function in Point class.
Using toString() method
public class Point {
public String toString()
{
//your code goes here
return "Point "+ "X : "+ x +"Y : "+ y + "Z : "+z;
}
}
As the previous answers already implicitly stated
System.out.println(p3);
actually is
System.out.println(p3.toString());
and since you are not providing an own implementation for the toString() method. The default implementation of Object is called. Which results in your given output. In order to change that behaviour you have to override toString()
#Override
public String toString() {
return "Point: x=" + x + ", y=" + y + ", z=" + z;
}
Related
I was reading a java book, where I came across this statement:
So, every subroutine is contained either in a class or in an object
I'm really confused why does it say "class or in an object"
I would like some explanation.
Let's try this example
public class Demo {
public static void classMethod() {
System.out.println("Call to static method");
}
public void objectMethod() {
System.out.println("Call to object method");
}
public static void main(String[] args) {
Demo demo = null;
demo.classMethod();
//demo.objectMethod();// throws NPE if uncommented
}
}
This code will work (even if the demo variable is null) because static method classMethod is contained within the class Demo. The commented line will throw a NullPointerException because the method objectMethod is not contained in the class but in the object so will need an instance of Demo class to call it.
Subroutine is a method written inside a class. We use them to do various tasks. That statement states that these methods/subroutines are written in an object or a class.
If we have an object instantiated, it will create new methods for every non-static method for that object which were defined in the class of the object. Hence those non-static methods/subroutines are in the object.
But if the class is a static class, we can't have any objects from it. But we can use subroutines/methods of that class. So, they are in a Class
That's what your statement says.
EDIT:
I thought to give an example for this.
public class ExampleClass {
public String getNonStaticString() {
return "This String is From Non-Static Method";
}
public static String getStaticString() {
return "This String is From Static Method"
}
}
Then, if you need to get the static String, all you have to do is
String staticString = ExampleClass.getStaticString();
Note that I havn't created an object from the ExampleClass Here. I just used the method.
But, if you need to get the String from the non-static method, you should instantiate an object first.
ExampleClass exampleObject = new ExampleClass();
String nonStaticString = exampleObject.getNonStaticString();
static methods also known as class method. Static method associated only with the class and not with any specific instance of that class(object).
So, every subroutine is contained either in a class or in an object
The statement is technically not 100% correct.
First of all, subroutines in java are commonly called methods. The following two terms are often used interchangeably:
Method: A subroutine working with an object instance, this.
Function: A subroutine not working with an object instance.
Here is an example scenario which should you get an idea what that means:
public class Circle {
//region static code
//we cannot call "this" in a static context, main(String[]) is no exception here
public static void main(String[] args) {
Circle a = new Circle(0, 0, 10);
Circle b = new Circle(10, 10, 2);
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("circumference of a = " + a.getCircumference());
System.out.println("circumference of b = " + b.getCircumference());
System.out.println("area of a = " + a.getArea());
System.out.println("area of b = " + b.getArea());
System.out.println("distance of a, b = " + distance(a, b));
System.out.println("a, b intersect = " + (intersects(a, b) ? "yes" : "no"));
}
//we cannot call "this" in a static context, but we have the circles a, b as parameters we can use to calculate their distance
public static double distance(Circle a, Circle b) {
return Math.sqrt(squared(a.x - b.x) + squared(a.y - b.y));
}
//we cannot call "this" in a static context, but we have the circles a, b as parameters we can use to check for an intersection
public static boolean intersects(Circle a, Circle b) {
return a.radius + b.radius > distance(a, b);
}
//we cannot call "this" in a static context, but we have the number x as parameter we can use to calculate the square of
public static double squared(double x) {
return x * x;
}
//we cannot call "this" in a static context, but we have the number radius as parameter we can use to check if its value is in range
public static void checkRadius(double radius) {
if(radius < 0) {
throw new IllegalArgumentException("radius must be >= 0");
}
}
//endregion
//region member / instance code
private double x;
private double y;
private double radius;
public Circle(double x, double y, double radius) {
checkRadius(radius);
this.x = x;
this.y = y;
this.radius = radius;
}
//region getters and setters
//we may refer to the instance variables with or without "this", sometimes it is necessary to clarify - see: setX(double)
public double getX() {
return x;
}
//we may refer to the instance variables with or without "this", but in this case we have two variables with name "x"
//if we write "x", the parameter is taken. for the circle's x coordinate, we need to clarify with "this.x"
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
checkRadius(radius);
this.radius = radius;
}
//endregion
//we may refer to the instance variables with or without "this", sometimes it is necessary to clarify - see: setX(double)
public double getCircumference() {
return 2 * Math.PI * radius;
}
public double getArea() {
return Math.PI * squared(radius);
}
//we may refer to the instance variables with or without "this", sometimes it is necessary to clarify - see: setX(double)
#Override
public String toString() {
return "circle at [" + x + ", " + y + "] with radius " + radius;
}
//endregion
}
Output:
a = circle at [0.0, 0.0] with radius 10.0
b = circle at [10.0, 10.0] with radius 2.0
circumference of a = 62.83185307179586
circumference of b = 12.566370614359172
area of a = 314.1592653589793
area of b = 12.566370614359172
distance of a, b = 14.142135623730951
a, b intersect = no
I'm practicing inheritance in Java and got stuck on getter method in subclass.
Here is the Point class:
package OOP.LinePoint;
public class Point {
private int x;
private int y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
public String toString() {
return "Point: (" + x + "," + y + ")";
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
Here LineSub class:
package OOP.LinePoint;
public class LineSub extends Point{
Point end;
public LineSub(int beginX, int beginY, int endX, int endY){
super(beginX, beginY);
this.end = new Point(endX, endY);
}
public LineSub(Point begin, Point end){
super(begin.getX(),begin.getY());
this.end = end;
}
#Override
public String toString() {
return "LineSub [begin=" + "(" + super.getX() +"," + super.getY() +") " + "end=" + end + "]";
}
public Point getEnd() {
return end;
}
public void setEnd(Point end) {
this.end = end;
}
public Point getBegin(){
}
public void setBegin(Point begin){
setX(begin.getX());
setY(begin.getY());
}
}
My problem:
1) toString() method. I'm trying to print two points(begin and end). As you can see end is easy but begin Point is inherited and idk what should I type. The way I'm getting x and y of point is working but for me it seems to be lame way of doing that. For sure there is a better way, could you please help me with that?
2) Point getBegin() method. I've tried:
public Point getBegin(){
return (Point)this;
}//Not working(getting whole Point object)
and
public Point getBegin(){
return new Point(getX(), getY());
}//Very noob way
I have no other ideas, please lend me your wisdom.
IMHO, it is not a good use of inheritance. Your case is not a valid candidate for Inheritance.
A class is a good candidate for inheritance only when it conforms to is-A relationship.
A Line is not a Point but it a collection of points (In your case it is being and end).
So, It is a good candidate for composition (Has-A).
A line HAS a begin and an end point. You are using both inheritance (For begin point) and composition (For end point) for code reuse.
Adhere to composition and have two points (begin and end) in Line class.
To get the start Point you must cast yourself to a Point. You can call your super.toString to access the toString of the parent class.
#Override
public String toString() {
return "LineSub [begin=" + super.toString() + "end=" + end.toString() + "]";
}
public Point getBegin() {
return (Point) this;
}
The fact that you have to cast is an indicator that you have your hierarchy wrong. This structure would normal be implemented using two points.
public class LineSub {
Point begin;
Point end;
New to Java.
I have an instance player1 of the Player class below.
Player player1 = new Player(0,0);
Inside the Player class I have composed an object coordinate of type Coord (defined below). When I instantiate player1 above "Player is at coordinate 0,0" is displayed as expected.
public class Player extends Entity {
public Coord coordinate;
public Player(int x, int y) {
Coord coordinate = new Coord(x,y);
System.out.println(“Player is at coordinate “ + coordinate.getX() + “,”
+ coordinate.getY());
}
}
The Coord class is defined as follows.
public class Coord {
private int x;
private int y;
public Coord(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
The problem arises when I try to access obj and its respective methods after I instantiate player1. When I try to access coordinate I get a NullPointerException error.
Player player1 = new Player(0,0);
System.out.println(“Player is at coordinate “ + player1.coordinate.getX() +
“,” + player1.coordinate.getY());
What am I doing wrong?
You aren't making Coord obj; a field of your class. That could be as simple as something like
public class Player extends Entity {
Coord obj;
public Player(int x, int y) {
obj = new Coord(x,y);
System.out.println(“Player is at coordinate “ + obj.getX() + “,”
+ obj.getY());
}
}
Note that obj is a terrible field name, and that it has default level access permission here. One way to improve that might be something like
public class Player extends Entity {
private Coord coordinates;
public Player(int x, int y) {
coordinates = new Coord(x,y);
System.out.println(“Player is at coordinate “ + obj.getX() + “,”
+ obj.getY());
}
public Coord getCoordinates() {
return coordinates;
}
}
Then you could use it like
Player player1 = new Player(0,0);
System.out.println(“Player is at coordinate “
+ player1.getCoordinates().getX()
+ “,” + player1.getCoordinates().getY());
You might also override toString() in the Coord class, then you could say
System.out.println(“Player is at coordinate “
+ player1.getCoordinates());
I'm pretty new in java and I'm doing a simple program but I don't know why I get different values, i.e., if I use getX, getY and getZ I get (6,5,8) but if I use toString I get different values for X and Y (3, 4, 8), so can anyone explain me why it happens because as far as I understand it should get the same values in both cases or what I'm doing wrong?
public class Coordinates {
private double coorX, coorY;
Coordinates()
{
coorX = 1;
coorY = 1;
}
Coordinates(double x, double y)
{
coorX = x;
coorY = y;
}
void setX(double x)
{
coorX = x;
}
void setY(double y)
{
coorY = y;
}
double getX()
{
return coorX;
}
double getY()
{
return coorY;
}
public String toString()
{
String myString = "(" + coorX + " , " + coorY + ")";
return myString;
}
public class Coordinates3D extends Coordinates{
private double coorZ;
Coordinates3D()
{
super();
coorZ = 1;
}
Coordinates3D(double x, double y, double z)
{
super(x,y);
coorZ = z;
}
public void setZ(double z)
{
coorZ = z;
}
double getZ()
{
return coorZ;
}
#Override
public String toString()
{
String myString = "(" + coorX + " , " + coorY + " , " + coorZ + ")" ;
return myString;
}
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Coordinates test1 = new Coordinates(3,4);
System.out.println(test1.toString());
System.out.println(test1.getX());
System.out.println(test1.getY());
Coordinates3D test2 = test1.new Coordinates3D(6,5,8);
System.out.println(test2.toString()); ---> here is the problem
System.out.println(test2.getX());
System.out.println(test2.getY());
System.out.println(test2.getZ());
}
}
First there is a problem on how you define the visibility of the fields of the super class:
public class Coordinates {
//defines as private
//sub classes cannot access to these fields directly
private double coorX, coorY;
This is that you cannot invoke super.coorX nor super.coorY on any sub class e.g. Coordinates3D. So, in toString method, when you have this code:
String myString = "(" + coorX + " , " + coorY + " , " + coorZ + ")" ;
It compiles and runs fine because Coordinates3D is an inner class. So, when using coorX here it's accessing to the value of coorX field stored in the instance of Coordinates class that created the instance of Coordinates3D. This can be easy to replicate if you separate the classes:
class Coordinates {
private double coorX, coorY;
}
public class Coordinates3D extends Coordinates {
//current code...
#Override
public String toString() {
//now you will get a compilaton error
String myString = "(" + coorX + " , " + coorY + " , " + coorZ + ")" ;
return myString;
}
}
The best solution would be:
mark the fields in the super class as protected
separate the classes
If you still want to keep Coordinates3D as inner class (not recommended), then:
mark the fields in the super class as protected
use super.coorX and super.coorY to not have the same unexpected behavior.
I would like to add to the existing answers that even in the class, you should not read the fields firectly, but use their getters.
#Override
public String toString() {
String myString = "(" + getX() + " , " + getY() + " , " + getZ() + ")";
return myString;
}
This also fixes the problem, but you should still not make the Coordinates3D class an inner class of Coordinates.
The following is a toy problem of my original problem. Bird is an interface. Cardinal is the subclass of Point and it implements the Bird interface. The Aviary class carries out the implementation.
Question: What should I put in the getPosition() instance method such that the Aviary class carries the getPosition() method correctly?
Please correct me if the abstract method in the bird interface is coded wrong.
public interface Bird{
public Point getPosition();
}
public class Point{
private int x;
private int y;
// Constructs a new Point at the given initial x/y position.
public Point(int x, int y){
this.x = x;
this.y = y;
}
// Returns the x-coordinate of this point
public int getX(){
return x;
}
// Returns the y-coordinate of this Point
public int getY(){
return y;
}
}
Question is in the following code:
public class Cardinal extends Point implements Bird{
// Constructors
public Cardinal(int x , int y){
this(x,y);
}
// not sure how to write this instance method
public Point getPosition(){
???????????
}
}
public class Aviary{
public static void main(String[] args){
Bird bird1 = new Cardinal(3,8);
Point pos = bird1.getPosition();
System.out.println("X: " + pos.getX() + ", Y: " + pos.getY() );
}
}
Just return the object itself:
public Point getPosition(){
return this; // returns a Point object
}
I gave an answer, but I am not sure if you have a design nightmare or a one-of-a-kind design simplification. A Point subclass implementing a Bird makes me bang my head on the wall, but having both types in one object will make the calculations pretty neat, (if you have massive calculations, that is). Because instead of bird.getPosition().getX(), you can write bird.getX().
Point bird1 = new Cardinal(3, 8);
Point bird2 = new Cardinal(4, 12);
// calculate the distance between two birds
double distance = Math.sqrt(Math.pow(bird2.getX() - bird1.getX(), 2) + Math.pow(bird2.getY() - bird2.getY(), 2));
But if your system is not a bird simulator that needs heavy calculations on birds represented by mere Point objects, I think you should use composition over inheritance.
public interface IBird {
public Point getPosition()
}
class Bird implements IBird {
private Point position;
public Bird(int x, int y) {
this.position = new Point(x, y);
}
public Point getPosition() {
return this.position;
}
}
// and then in main()
Bird bird = new Bird(3, 8);
Point pos = bird.getPosition();
System.out.println("X: " + pos.getX() + ", Y: " + pos.getY() );
The Cardinal class objects have an is-a relationship with the Point class objects, so you could just return this; as Krumia suggested.
P.S. you can use the super keyword when referring to a superclass within a subclass to access it's protected and public methods.