public class InitializationTest {
private int x;
private int y;
private int sumOFXandY = x + y;
public InitializationTest(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getSumOFXandY() {
return sumOFXandY;
}
}
class Tester {
public static void main(String[] args) {
InitializationTest initializationTest = new InitializationTest(5, 6);
System.out.println(initializationTest.getX());
System.out.println(initializationTest.getY());
System.out.println(initializationTest.getSumOFXandY());
System.out.println(initializationTest.getX() + initializationTest.getY());
}
}
Output:
5
6
0 //Why not 11?
11
In the example above my brain cannot understand such simple thing - a revelation.
When the class is created, its fields are initialized with default values. In this case those are 0.
Upon calling the constructor x is initialized with 5 and y is initialized with 6. Why then sumOFXandY is somewhere aside and still is initialized with 0 even after calling the constructor. Why is not it initialized with 5 + 6 = 11 ?
Because it(sumOFXandY) cannot be re-initialized after the constructor gets executed. When you create an object, it initializes the instance variables that are initialized inline (here it is sumOFXandY = x + y). Then the constructor block gets executed.
To solve this, move sumOFXandY = x + y inside the constructor.
Related
This question already has answers here:
What is object field initialization and constructor order in Java
(3 answers)
Are fields initialized before constructor code is run in Java?
(5 answers)
Primitives/Objects Declaration, default initialization values
(1 answer)
Closed 4 months ago.
why is the output 0.0 if I write the following code? It seems to me like it wouldn't read the variable x inside my class Car.
public class Car {
double x = 2;
double y;
double v = x * y;
public Car(double y) {
this.y = y;
}
public static void main(String[] args) {
Car car = new Car(100);
System.out.println(car.v);
}
}//end of class
The v is being calculated before the y is set in the constructor, so it will always equal 2*0, so 0.
You can do the v calculation inside the constructor instead.
public class Car {
double x = 2;
double y;
double v;
public Car(double y) {
this.y = y;
v = x * y;
}
}
your double v = x * y line is being done on instantiation of a car object, when x is 2 and y is unititialized (0). You need to move that line into the constructor if you want it to update with the proper value.
I have included some System.out inside the constructor to get the flow of the execution.
Here, the value of v is already assigned with value of x and y where x = 2 and y = 0.0.
So,you can modify your code as below:
Code:
Car.java
public class Car {
double x = 2;
double y;
double v;
public Car(double y) {
System.out.println("Inside constructor");
System.out.println("value of v here:" + v);
this.y = y;
v = x * y;
System.out.println("value of v now:" + v);
}
}
Test.java
public class Test {
public static void main(String[] args) {
Car car = new Car(100);
System.out.println(car.v);
}
}
Output:
Inside constructor
value of v here:0.0
value of v now:200.0
200.0
Im trying to add my anonymous objects from a class to a Hashtable. I created my Hashtable as my teacher wants but there is one problem. I have to get x and y values one of my Objects. But System cannot find x anyway.
public class HashDatastructure{
public static void main(String[] args){
java.util.Hashtable kreise = new java.util.Hashtable();
for(int i = 0; i < 6; i++){
kreise.put(new Integer(i), new Kreis(120, 120, 60));
}
System.out.println(kreise.get(3).toString() + " is 4. Object
and this Object's X Value: "
+ kreise.get(3).x + " || Y Value: ");
}
}
And here it is my Kreis Class:
public class Kreis extends Object{
public int x; //Mittelpunkt-x
public int y; // Mittelpunkt-y
public int radius;
public final double PI = 3.14159; //Constant Variable for pi
public static int kreisCounter = kreisZaehler();
public static int counter = 0;
public Kreis(int x, int y, int radius){
this.x = x;
this.y = y;
this.radius = radius;
kreisCounter();
}
private static int kreisZaehler(){
counter++;
return counter;
}
public void setRadius(int wert){
radius = wert;
}
public double getFlaeche(){
return radius * radius * PI;
}
public double getUmfang(){
return 2 * radius * PI;
}
}
I don't know what you mean by "anonymous objects," but you're using raw types, which is generally not a good idea. Instead, tell the compiler what kind of object kreis contains:
java.util.Hashtable<Kreise> kreise = new java.util.Hashtable<>();
// ----------------^^^^^^^^---------------------------------^^
Then, the compiler will know that get returns a Kreis object, which has x and such. (Side note: Probably better to make x private and provide an accessor like getX for it.)
More to explore in the Generics Java Tutorial.
If for some reason you have to use raw types, you can cast to Kreis on retrieval:
// NOT recommended
System.out.println(kreise.get(3).toString() + " is 4. Object and this Object's X Value: "
+ (((Kreise)kreise.get(3)).getX() + " || Y Value: ");
// -----------------^^^^^^^^^-------------^-^^^^^^
(Note I'm assuming you make x private and provide an accessor for it.)
This question already has answers here:
What causes error "No enclosing instance of type Foo is accessible" and how do I fix it?
(11 answers)
Closed 7 years ago.
Help Please....
I am new in Java. I am trying to write a code that contains a class "point" into a public class "PeterAndSnowBlower" in Eclipse(Luna).
I have also tried by making the variables x, y public in the class "point" and it gives the same error.
I have also used this.x and this.y instead of x and y inside the constructors
Here is my code:
import java.util.*;
public class PeterAndSnowBlower {
class point{
int x;
int y;
public point() {
x = y = 0;
}
public point(int a, int b){
x = a;
y = b;
}
public point(point p) {
x = p.x;
y = p.y;
}
public double distance(point P){
int dx = x - P.x;
int dy = y - P.y;
return Math.sqrt(dx*dx + dy*dy);
}
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int n, x, y;
point P = new point(0, 0);
n = in.nextInt();
P.x = in.nextInt();
P.y = in.nextInt();
Vector<point>points = new Vector<point>();
for(int i = 0; i < n; i++){
x = in.nextInt();
y = in.nextInt();
points.add(new point(x, y));
}
double r1, r2;
r1 = r2 = P.distance(points.get(0));
for(point point:points){
r1 = Math.max(r1, P.distance(point));
}
}
}
the error is:
Multiple markers at this line
- No enclosing instance of type PeterAndSnowBlower is accessible. Must qualify the allocation with an enclosing instance of type PeterAndSnowBlower (e.g.
x.new A() where x is an instance of PeterAndSnowBlower).
- The constructor PeterAndSnowBlower.point(int, int) is undefined
Unless the inner class is defined static, you cannot instantiate it from static method from outer class. The non-static class requires this reference to outer class.
Here it makes sense to declare this class as static. Obviously it doesn't refer to outer class.
You're statically accessing your inner class (meaning you don't do it from an instance of the outer class).
What you need is a static inner class, which makes perfect sense here as the inner class doesn't refer to the outer one.
Change the declaration to
static class point {
I'm following a book and I have a Point class which defines a point and I am trying to display the values. I've been looking around for a while now, whatever I do it always displays [0,0] here's my code.
class Main {
public static void main(String []args) {
Point point = new Point(10, 20);
System.out.println(point.toString());
}
}
class Point {
private int x, y;
public Point(int x, int y) {
x = x;
y = y;
}
public String toString() {
return "[" + x + ", " + y + "]";
}
You're never initializing class members x and y actually. So they're initialized as 0 automatically hence the [0,0] output.
x = x means parameter x = parameter x which does nothing.
use this.x = x; instead so Point class member x will be set.
Look at your constructor:
public Point(int x, int y) {
x = x;
y = y;
}
In your case you do not initialize class fields. To do that, use this keyword and it should look like:
public Point(int x, int y) {
this.x = x;
this.y = y;
}
Otherwise you are dealing with parameter x and y variables only.
Use this in Constructor as below :-
class Point {
private int x, y; // These x and y are member of Point class
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return "[" + x + ", " + y + "]";
}
You are not initializing x and y of Point class.
In toString() method you are printing x and y of Point class which are not initialized and hence taking default value of 0 i.e. 0 is default value of integer.
use the this keyword for the separation of local variable and instance variable. in your parameterized constructor jvm is not able to initialize the instance variable because it gets an ambiguity problem between local and instance variable. And instance variable in java gets implicitly initialized if u we are not initializing that's why you are getting [0,0] as the output.
here is the code..
class Main {
public static void main(String []args) {
Point point = new Point(10, 20);
System.out.println(point.toString());
}
}
class Point {
private int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return "[" + x + ", " + y + "]";
}
In your Constructor for the Point object:
public Point(int x, int y) {
this.x = x;
this.y = y;
}
You will need to put this.x to indicate you are setting the value of the Point object's x variable, not the x argument passed into the constructor.
The updated, functional code is below:
class Main {
public static void main(String []args) {
Point point = new Point(10, 20);
System.out.println(point.toString());
}
}
class Point {
private int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return "[" + x + ", " + y + "]";
}
Is there a way to have a static method such that it returns a Vector object (with a simple integer x and y value as fields) which is a Vector multiplied by an int value argument. However, there are no new objects made, i.e, the object assigned to the return value is changed instead of there being a new Vector created?
The following code does not achieve this:
public class Vector{
public int x,y;
public Vector(int x,int y){
this.x = x;
this.y = y;
}
//Important code starts
public static Vector mult(Vector v,int a){
return new Vector(v.x*a,v.y*a);
}
//Important code stops
}
This code is what I'm after but it's too messy:
public static Vector mult(Vector v1,Vector v2,int a){
v1.x = v2.x*a;
v1.y = v2.y*a;
}
Is there an alternative?
Why not add:
public void multiply(Vector otherVector, int a){
x = otherVector.x * a;
y = otherVector.y * a;
}
to your Vector class.
Do you mean?
public void mult(double a) {
x *= a;
y *= a;
}