I have a class that creates the object of type Smo. The object then calls a static method from another class. The static method requires that I pass the object to it that is calling it. How do I designate the calling object as the parameter to pass.
For example:
class Smo {
Smo() {
}
void sponge() {
car.dancing(??????); //////< ----------- how do I refer to self?
}
void dance() {
//// do a little dance
}
}
class Car() {
Car() {
}
dancing(Smo smo) {
smo.dance();
}
}
Use the this keyword.
car.dancing(this);
use the keyword 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.
Use this to have an object refer to itself. So,
car.dancing(this);
yup: car.dancing(this);
been there done (this) :D
Related
I have created an instance of an object in one of my classes for a Java program. How can I pass the same instance of that object to another class?
Would I need to do something like creating some type of a getter method in the original class to pass the object through to the other class?
To "pass" it you need a method or a constructor in the other class that can accept it:
public class Other {
// either
public Other(MyClass obj) {
// do something with obj
}
// or
public void method(MyClass obj) {
// do something with obj
}
}
Then call the constructor/method:
MyClass x = new MyClass();
Other other = new Other();
other.method(x);
There are many ways to pass the reference for one object to another object. The simplest and most common ways are:
as a constructor parameter,
as a parameter of a setter method; e.g. setFoo(Foo foo) to set the "foo" attribute, or
as an "add" method in the object being passed is going to be added to a collection; e.g. addFoo(Foo foo).
Then there are a variety of more complicated patterns where objects are passed using publish/subscribe, call-backs, futures, and so on.
Finally there are some tricks that can be used to "smuggle" objects across abstraction boundaries ... which are generally a bad idea.
You can pass the object via the constructor of the other class.
Simple Example:
Class A{
}
Class B{
A a;
public B(A obj){
this.a=obj
}
}
Let's assume you want to pass an object of class A to class B. Now you have created the object like this:
A object = new A ();
And now in your B class, you can write a method to accept a A object. It should be public and you can make it static if you like.
If you want to pass object to B, you must want to do something with it, right? So you should name your method accordingly. You probably want to assign a field of type A (Let's call this fieldA) in B. (or maybe that isn't what you want, but I'll use this for the example)
Let's look at the method:
public void setFieldA (A a) {
fieldA = a;
}
You can call this method as follows:
anObjectOfClassB.setFieldA (object);
Of course you don't need anObjectOfClassB if it is static.
How can I have the Edit() method be called by default when I construct a Breuk object?
public class Breuk {
public Breuk() {//constructor
}
private static Breuk Edit (Breuk b){ //function
}
}
Every time a new Breuk object is created, the Edit() method is called by default since it is placed inside the constructor. As the method is static, it has to be called in a statically way, i.e. ClassName.staticMethod(). As the method expects a Breuk object as argument, you pass this reference to it, meaning the object that's being constructed.
By the way, all method names should be lowercase according to Java conventions. So, consider renaming Edit(...) to edit(...).
class Breuk {
int x;
int y;
public Breuk(int x, int y) {
Breuk.Edit(this);
}
private static void Edit(Breuk b){
//edits breuk
}
}
First of all, you should stick to Java naming conventions, which state that method names should be lowerCamelCase. So you should rename your Edit() method to edit().
If you want the edit() method to be called by default when constructing an instance of the Breuk class, you can use an initializer block.
Excerpt from the Java Tutorial:
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
For your example, you could try something like this:
public class Breuk {
{ // initializer block
Breuk.edit(this); // always called by default,
// no matter which constructor is used
}
public Breuk() { // no-args constructor
}
public Breuk(int a1, int a2) { // another constructor
}
private static Breuk edit(Breuk b) { // function
}
}
Here I'm assuming you want to pass the instance being constructed to the edit() method, that's why this is passed as an argument.
EDIT:
In case this assumption is true, I suggest you make the edit() method return void, as you can't assign an instance to this, since it's final (and it doesn't make any sense, either).
Just call the method from the end of your default constructor. There's no need to think about any "default" calling here. Just implement it.
public class Breuk {
public Breuk() {
// constructor
edit(this);
}
private static Breuk edit (Breuk b){
// class-level processing on any Breuk that is constructed
}
}
I am naive to java programming.
How to access an object created in one class into another class.
Class A
{
Obj
}
Class B
{
//Here i want to use Obj
A.Obj
}
For the above i declare Obj as public static, but when i use it in Class B as A.Obj, it is returning a syntax error saying
"Cannot make a static reference to the non-static field A.Obj".
Am i missing something here? Are there any other ways?
Yes you cant access without having an instance of A. You could do something like:
System.out.println(new A().Obj);//or define Obj as static in A class.
Note - You should encapsulate your Obj and access it via getter method.
You should use provide a get method or use that object in static method as well. for your information static will not garbage collected unless the execution gets stopped for more about your answer use this answer's reference
You need first to declare your Obj in class A as static
class A {
static Object object = new Object();
}
Then you can use it
class B {
A.object //in the class cannot be accessed directly
Object x = A.object; //can use it to assign a value
public Object Foo() {
A.object //in a method can be accessed directly
return A.object; //here as expression result
}
}
At present I have a class that is calling the static method of a different class. What I am trying to do however is have the static method change a variable of the calling class, is that possible?
Example code:
public class exClass {
private int aVariable;
public exClass() {
othClass.aMethod();
}
}
public class othClass {
static void aMethod() {
// stuff happens, preferably stuff that
// allows me to change exClass.aVariable
}
}
So what I would like to know is, if there is a way to access aVariable of the instance of exClass that is calling othClass. Other than using a return statement, obviously.
Not if aClass doesn't expose that variable. This is what encapsulation and information hiding are about: if the designer of the class makes a variable private, then only the component that owns it can modify or access it.
Of course, the dirty little secret in Java is that reflection can get you around any private restriction.
But you should not resort to that. You should design your classes appropriately and respect the designs of others.
You can pass this as a parameter to the second function.
public class exClass {
public int aVariable;
public exClass()
{
othClass.aMethod(this);
}
}
public class othClass{
static void aMethod(exClass x)
{
x.aVariable = 0; //or call a setter if you want to keep the member private
}
}
you should gave the static method in othClass the instance of exClass like othClass.aMethod(this), then you can change the variable of that instance, or make the variable static if you dont need an instance
As we know that we do not have to add any return type to a Java constructor.
class Sample{
.....
Sample(){
........
}
}
In Objective C, if we create a constructor, it returns a pointer to its class. But it is not compulsory, I think.
AClass *anObject = [[AClass alloc] init];//init is the constructor with return type a pointer to AClass
Similarly, Is the constructor converted to a method which return a reference to its own class??
Like this:
class Sample{
.....
Sample Sample(){
........
return this;
}
}
Does the compiler add a return type a reference to same class to constructor?
What is happening to a constructor?
Any reference to study this?
EDIT:
Actually i want the answers to be at byte code level or JVM level or even below.
Many have answered how constructors are defined in Java.
At the JVM level, static initialisers and constructors are methods which return void. Static initialisers are static methods, however constructors use this and don't need to return anything. This is because the caller is responsible for creating the object (not the constructor)
If you try to only create an object in byte code without calling a constructor you get a VerifyError. However on the oracle JVM you can use Unsafe.allocateInstance() to create an object without calling a constructor,
The static initialiser is called <cinit> which takes no arguments and the constructor is called <init>. Both have a void return type.
For the most part, this is hidden from the Java developer (unless they are generating byte code) however the only time you see these "methods" in stack traces (though you can't see a return type)
While constructors are similar to methods, they are not methods. They have no return type, are not inherited, and cannot be hidden or overridden by subclasses.
Constructors are invoked by class instance-creation expressions (basically, the use of new), by explicit invocation from other constructors (using this(...) or super(...) syntax), and by the string concatenation operator. There is no other way to invoke a constructor (in particular, they cannot be invoked like other methods).
See Section 8.8 of the Java Language Specification for more info.
Is the constructor converted to a method which return a reference to its own class??
No but yes, if it is specified to do so.
Does compiler add a return type a reference to same class to constructor ??
No it does not
What is happening to a constructor??
It is the method, which runs when the object is created. Typically, by using "new" keyword. It Might perform some preliminary task, or return something or assign some values during construction.
Any reference to study this.??
http://www.javaworld.com/javaworld/jw-10-2000/jw-1013-constructors.html
http://www.javabeginner.com/learn-java/java-constructors
Constructors are similar to methods except that they use the name of the class and have no return type. The whole purpose of using constructors is to create an object (an instance of a class) and allocate it (via new keyword) in the memory (the heap) and also initialize any fields if available.
Constructors are invoked via the special java keyword new, which creates (and initializes) an object of the specified concrete type.
I suppose you could say the combination of new and the chosen constructor "returns" an object, which in java is of course a pointer under the covers
Constructor returns the class reference of the class for which its being called.E.g.-
class A {
int x;
A(int a) {
x = a;
}
}
class B {
public static void main(String asd[]) {
A a = new A(4);
System.out.println(a);
}
}
Here after calling the constructor A(...), this constructor will return the reference of type of class A to caller( i.e. A a = new A(4) ).
The return type of the constructor is corresponding class type.
package com.ie.test;
import java.lang.reflect.*;
public class a {
public a() {
super();
System.out.println("*** no-arg constructor ***");
}
public static void main(String[] args) {
Constructor[] constructors = a.class.getConstructors();
for (Constructor constructor:constructors) {
int i = constructor.getModifiers();
AnnotatedType annotatedType = constructor.getAnnotatedReturnType();
System.out.println("***********Returntype *******"+annotatedType.getType());
System.out.println("*******constructor *****"+Modifier.toString(i));
}
Method[] methods = a.class.getDeclaredMethods();
for (Method method:methods) {
int i = method.getModifiers();
// Class c = method.getReturnType();
AnnotatedType annotatedType = method.getAnnotatedReturnType();
System.out.println("***********Returntype *******"+annotatedType.getType());
// System.out.println(c);
System.out.println("*******methods*******"+Modifier.toString(i));
}
}
public int m1() {
System.out.println("***************");
return 0;
}
}