When the 'this' operator is used to reference a variable in the current object is that included in the constructor? For example...
public class Mechanics {
public Mechanics() {
int x = 1;
}
public int returnX(){
return this.x;
{
}
As the constructor is called when the object is created will the 'this' operator return the x in the constructor or only a variable that is outside?
Thanks
Your code is not valid and won't compile. x as defined in the constructor is local to the constructor only. It is not a field of the Mechanics class. To be able to use x somewhere else, you need to declare it as a field of the class:
public class Mechanics {
private int x;
public Mechanics() {
this.x = 1; //initialize x in the constructor
}
public int returnX() {
return this.x;
}
}
This is just as well, because with the behavior that you are expecting, any local variable you declare inside any member method of a class (including the constructor) would turn into a field of the owning class. This is a recipe for anarchy.
X is local variable inside constructor, and it doesn't exist after constructor finished it's work. Your code will not compile.
"this" is just a reference to object of this class. Is it possible to get value of some local variable inside other method? No, no matter how You try.
You need class field, that is visible to all methods.
The scope the variable x is restricted to the constructor.
If you want access to x in returnX you could do so:
public class Mechanics {
private int x;
public Mechanics() {
this.x =1;
}
public int returnX(){
return this.x;
}
}
Related
For example:
In Class One
int killcount = 0;
In Class Two
killcount = 5;
All I want to do I get the variable from one class to another class. How would I do that?
Before trying to work with Bukkit I'd recommend you to get some Java experience first. That's not meant as an insult, but it can get quite confusing if you do it the other way round. Anyways, if you still want to know the answer to your question:
You'll have to create a getter & setter for your "killcount" variable.
class Xyz {
private int killcount;
public void setKillcount(int killcount) {
this.killcount = killcount;
}
public int getKillcount() {
return this.killcount;
}
}
Of course this is a simplified version without checks, but if you want to access the variable from a different class you can create an instance and use the methods to modify it.
public void someMethod() {
Xyz instance = new Xyz();
instance.setKillcount(instance.getKillcount() + 1);
//this would increase the current killcount by one.
}
Keep in mind that you'll have to use the same instance of the class if you want to keep your values, as creating a new one will reset them to default. Therefore, you might want to define it as a private variable too.
Consider the examples
public class Test {
public int x = 0;
}
This variable x can be accessed in another class like
public class Test2 {
public void method() {
int y = new Test().x;
// Test.x (if the variable is declared static)
}
}
Ideally, the instance variables are made private and getter methods are exposed to access them
public class Test {
private int x = "test";
public int getX() {
return x;
}
public void setX(int y) {
x = y;
}
}
I've been reading about instance initializers in Java, and it's been explained that code common to all constructors can be put into them because they are called every time a new instance of a class is created. Is there an equivalent of instance initializers that run after constructors, for code that would be common to all constructors, but depends on what happens in the constructors?
No, there isn't an exact equivalent. If you want to run some common code, you can always factor out a method and call it at the end of all your constructors:
public class C {
private int x = 5;
private String y;
public C(int x) {
this.x = x;
endConstructor();
}
public C(String x) {
this.x = x.length;
endConstructor();
}
private void endConstructor() {
y = x + "!";
}
}
Sometimes, what seems like a situation where you want to call the same code at the "end" of all constructors can be refactored so that this code is in a single main constructor. Then, all other constructors call it using this(). For the example above:
public class C {
private int x = 5;
private String y;
public C(int x) {
this.x = x;
y = x + "!";
}
public C(String x) {
this(x.length);
}
}
The main constructor can be private, if appropriate.
Something like the #PostConstruct annotation can be used.
If your class has its dependencies injected using setter methods, then its constructor won't fully initialize an instance. Thus, additional "initializations" need to be performed after all the setter methods have been called.
If you think something happens in constructor:
class X {
private int x;
public X() {
// Code that sets x
// =-=-= HERE =-=-=
}
}
Insert the code you want to happen after the constructor... At the end of constructor.
If you have many constructors and don't want to duplicate code:
class X {
private int x;
public X() {
// Code that sets x
init();
}
public X(int x2) {
x = x2;
init();
}
private void init() {
// =-=-= HERE =-=-=
}
}
If every constructor invokes init, we may say this is invoked as a part of constructor, not after it. Imagine a train with one additional car following it, 50cm from it. Both have the same destination/time. Why couldn't we connect the train with standalone car?
Sometimes in a constructor, no statement is given. What does that indicate? For example if i create a class CIRCLE, then inside the class i write CIRCLE() {}, that is nothing is written inside. Can anyone explain it?
If your question is "why would anyone write such a constructor", then the answer is that the no-args default constructor only exists if no other constructor is specified.
Consider the following class.
class Foo {
int x;
}
As written, someone could write the following code to construct Foo.
Foo foo = new Foo();
However, now suppose I added a constructor which takes arguments.
class Foo {
int x;
public Foo(int x) {
this.x = x;
}
}
Now, suddenly, Foo foo = new Foo(); no longer works. To restore it, I must add the empty constructor again.
class Foo {
int x;
public Foo(int x) {
this.x = x;
}
public Foo() { }
}
Now, What if there are no other constructors that take arguments?
In that case, it is generally as the other answers suggest, to restrict access to constructing the class.
In the following definition of Foo, nobody is allowed to construct Foo. Perhaps Foo is meant only as a static class.
class Foo {
int x;
private Foo() { }
}
In the protected case, only subclasses can construct Foo.
class Foo {
int x;
protected Foo() { }
}
If there is no code in the constructor, chances are, it was declared to change the access to the constructor. By default, constructors are public. If you wanted to make it private, protected or package-private, you must explicitly declare it and manually change the modifier.
class Example {
public static void main(String[] args) {
new Demo(); //this is currently allowed
}
}
class Demo {
}
In order to prevent the creation of a Demo object within Example, we could declare Demo's constructor amd make it private:
class Demo {
private Demo() { }
}
Another reason could be that the class has a constructor that requires parameters. If so, you must explicitly declare the no-arg constructor to be able to use it.
If nothing is written, then when a new Object of that type is created, nothing 'extra' is done, whereas if in the constructor has code in, it does something.
For example, the following consructor for a class called 'Bank' assigns the argument 'name' to the field 'bankName', then instantiates a Terminal and 2 bank accounts:
private static final int INITIAL_BALANCE = 200;
public Bank( String name )
{
bankName = name;
atm = new Terminal();
account1 = new BankAccount( INITIAL_BALANCE );
account2 = new BankAccount( INITIAL_BALANCE );
}
It's a default constructor. For instance if you go:
Circle circle = new Circle();
You are then calling the default constructor. When you go ... Circle() that is a call to the default constructor, the one with no parameters.
The point of this is just to 'construct' an object or instantiate a class (instantiate just means create an object which is an instance of the class) with no additional information i.e. parameters.
This would generally be used to initialize fields to their default values, like so:
public Circle() {
this.x = 0;
this.y = 0;
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
this and super in java
I'm new to development. Something that I'm still unable to understand is the difference between this and super keywords. If there are any answers, it would be highly appreciated. Thanks.
this
Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
super
If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged).
super refers to the base class that the current class extends. this refers to the current class instance.
So, if Parent extends Child and you create a new Child(), super refers to the Parent class (and doing something like super() in the constructor would call the parent's constructor) and this refers to the actual Child instance you created with new.
Super refers to the superclass that a class extends. this refers to the current instance of a class.
These concepts can be confusing for new developers, they will be more clear when you learn about extending classes (inheritance). Sometimes when you refer to a variable or method, you might be being ambiguous for example if you repeated a class variable name in a method, the compiler won't know which variable you are referring to, so you can use this to specify you are referring to the current class's variable (not the local variable). The following would be ambiguous (and WRONG):
class Bike
{
int speed = 10;
public setSpeed(int speed)
{
speed = speed;
}
}
The compiler would have no idea what you intended, and will probably insult you with a cryptic (for a new developer) error message. Using this in the following way tells the compiler "I am referring to the class level variable, NOT the method level variable"
class Bike
{
int speed = 10;
//Constructors and shiz
public void setSpeed(int speed)
{
this.speed = speed;
}
}
(Although in practice you shouldn't duplicate variable names in this way!)
So to summarise, this tells the compiler that you're referring to the CURRENT class. Further ambiguity can arise when you extend classes (inherit functionality for a parent or super class), because the option of overriding the parent method arrises.
class Bike
{
public Bike()
{}
public void printSpeed()
{
System.out.println("This generic bike can go 10 m/s!!");
}
}
Now if we were to extend the bike class by introducing a more specific type of bike, we may want to override the printSpeed method to give the speed of our shiny new bike, like so:
class MountainBike extends Bike
{
public MountainBike() {}
public void printSpeed()
{
System.out.println("WHOAAAH!! MOUNTAIN BIKE GOES 100 m/s!!");
}
public void printGenericSpeed()
{
super.printSpeed();
}
}
The super.printSpeed() tells the compiler to run this method from the parent class, so a call to super.printSpeed() would actually call the printSpeed() method in the Bike class. The following code:
public static void main(String args[])
{
MountainBike mb = new MountainBike();
mb.printSpeed();
mb.printGenericSpeed();
}
will print
WHOAAAH!! MOUNTAIN BIKE GOES 100 m/s!!
This bike can go 10 m/s!!
Note that if we had not overridden the printSpeed() method, calling the following would be a call to the printSpeed() method of the Bike class.
public static void main(String args[])
{
MountainBike mb = new MountainBike();
mb.printSpeed();
}
would print
This bike can go 10 m/s!!
So to conclude, we use this to refer to the current class we're in, and super to refer to the parent of the class we're in.
In Java the keyword this refers to the current object of a class, like in:
class Point {
public int x = 0;
public int y = 0;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return x + "," + y;
}
}
class Point3D extends Point {
public int z = 0;
public Point(int x, int y, int z) {
super(x,y);
this.z = z;
}
public String toString() {
return super.toString() + "," + z;
}
}
In the constructor of the class Point this.x refers to the x defined in the class, where x is the parameter passed into the constructor. Here this is used to resolve the ambiguity of the name x. The same thing is true for y.
In the class Point3D the method toString() uses the return value of the super class Point to produce its own return value.
this: is the reference to the current object in the methods of its class. Refer to any member of the current object through the this keyword.
super: is the derived class' parent when your class extends it through the extend keyword, and you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a protected fields.
this keyword refers to the current instance at that point in time.
super keyword refers to the parent/super class of the current class.
EX:
class Test
{
Test()
{
}
Test(int i)
{
System.out.println("i=" + i);
}
}
class Sample extends Test
{
int i;
void Sample(int i) //constructor
{
this.i=i; // referring class version of the i using 'this'
super(i); // passing parameter to Super/Parent class constructor.
}
}
Is it possible, in Java, to access fields of an object that is passed as a parameter in a method?
Example code:
void myMethod(ArrayList<Integer> list, MyClass object) {
Integer myInt = object.x; // x is an Integer-type field in the object
}
I tried the following:
MyClass curObj = (MyClass)object; to no avail.
Any suggestions?
When I use javac to compile, I get a cannot find symbol error.
If I understood the question correctly why simply not access object directly? e.g. if object had a member memberName and methodName() method, which are public, you could simply do
void myMethod(ArrayList<Integer> list, MyClass object) {
object.memberName = "member Name"
object.methodName();
}
You don't have to cast your 'object' as it is only object in name, you are getting passed a MyClass Object.
And by that I mean you are getting MyClass object not Object object
To access x like that make it sure it is public, BUT you should make an accessor method in MyClass:
public Integer getX()
{
return x;
}
and change your line to:
Integer myInt = object.getX();
No reasons it shouldn't work unless
object is null (but this would be a run-time, not compile-time error)
x is not public and myMethod is not a method of the MyClass class
Yes, it is possible if your attribute is declared as public. For example:
public class MyClass {
public int test;
}
class Test {
public printMyClass( MyClass c ) {
System.out.println( c.test );
}
}
Or you can have one method that returns test value and only MyClass can modify test attribute (better).
public class MyClass {
private int test;
public int getTest() {
return test;
}
}
class Test {
public printMyClass( MyClass c ) {
System.out.println( c.getTest() );
}
}
Only if MyClass.x is a public, then yes. Otherwise, you can reach it via that property's getter/setter methods. Java is actually passing a copy of the reference to the object, so while the called method is working only with the reference copy, the underlying object is the same whether you access it via a reference or a copy of the reference. The state of the object is also exposed for potential changes from within the called method.
Of course Your example code should work as is.
See that the field x has the word public in your MyClass.
//In MyClass
public Integer x;
If you don't declare it public you have to provide a getter method. This is the normal case (private + getter) JAVA Bean...
//In MyClass
private Integer x;
public Integer getX()
{
return x;
}
void myMethod(ArrayList<Integer> list, MyClass object) {
Integer myInt = object.getX(); // x is an Integer-type field in the object
}