Sending my current object to another class - java

Sorry if the wording of the title isn't correct. Say I have a class and I have initialized an object of that class, now in the constructor for that class I want to pass that new object's values to another class, is there a way to do this?
Example:
public class testinger
{
public static void main(String[] args)
{
prep ab = new prep(10);
}
}
class prep
{
private int a;
prep(int x)
{
a = x;
complete tim = new complete(/*how to send my current prep object there?*/);
}
public int getA()
{
return a;
}
}
class complete
{
complete(prep in)
{
in.getA();
}
}

You can refer to the current instance using the this keyword.
prep(int x)
{
a = x;
complete tim = new complete(this);
}

use the the keyword complete tim = new complete(this);
For example in Java this is a keyword. It can be used inside the Method or constructor of Class. It(this) works as a reference to the current Object whose Method or constructor is being invoked. The this keyword can be used to refer to any member of the current object from within an instance Method or a constructor
read more details here

Related

Java Inheritance issue with static and non-static context

Please help me I am facing bit problem in Java code.
I am not able to understand how to fix the error.
Please help.
public class A {
private int a = 100;
public void setA(int value) {
a = value;
}
public int getA() {
return a;
}
}
public class B extends A {
private int a = 222;
public static void main(String[] args) {
System.out.println("in main(): ");
a = 123;
System.out.println("a = "+super.a );
}
}
The error I get is:
int a in class Main must be static
First of all, you should tell us the error :).
It looks like you are trying to access a variable in a non-static context from a static context (main method is static).
You should do something like below:
public class B extends A {
public static void main(String[] args) {
B b = new B();
b.setA(123)
System.out.println("a = " + b.getA());
}
}
It doesn't make sense to declare another 'a' variable in the child class. If you want to access 'a' directly, you can declare the field in class A as protected.
First of all, just to be clear prior to going to the code, your 2 classes, given they are both public, must be in their own separate files.
Now let's go to your code. The error lies first in this statements inside your main method:
a = 123;
You are accessing B's instance variable a from a static context -this is one.
Second:
System.out.println("a = "+super.a );
A's instance variable a is never inherited by B because it has a private access modifier.
If you want to access A's a, you could create an instance of A, and use that to call the getA() method which returns the value of A's a
Cheers,

Trouble with a constructor [duplicate]

I wrote this simple class in java just for testing some of its features.
public class class1 {
public static Integer value=0;
public class1() {
da();
}
public int da() {
class1.value=class1.value+1;
return 5;
}
public static void main(String[] args) {
class1 h = new class1();
class1 h2 = new class1();
System.out.println(class1.value);
}
}
The output is:
2
But in this code:
public class class1 {
public static Integer value=0;
public void class1() {
da();
}
public int da() {
class1.value=class1.value+1;
return 5;
}
public static void main(String[] args) {
class1 h = new class1();
class1 h2 = new class1();
System.out.println(class1.value);
}
}
The output of this code is:
0
So why doesn't, when I use void in the constructor method declaration, the static field of the class doesn't change any more?
In Java, the constructor is not a method. It only has the name of the class and a specific visibility. If it declares that returns something, then it is not a constructor, not even if it declares that returns a void. Note the difference here:
public class SomeClass {
public SomeClass() {
//constructor
}
public void SomeClass() {
//a method, NOT a constructor
}
}
Also, if a class doesn't define a constructor, then the compiler will automatically add a default constructor for you.
public void class1() is not a constructor, it is a void method whose name happens to match the class name. It is never called. Instead java creates a default constructor (since you have not created one), which does nothing.
Using void in the constructor by definition leads it to not longer be the constructor.
The constructor specifically has no return type. While void doesn't return a value in the strictest sense of the word, it is still considered a return type.
In the second example (where you use the void), you would have to do h.class1() for the method to get called because it is no longer the constructor. Or you could just remove the void.
This is arguably a design flaw in Java.
class MyClass {
// this is a constructor
MyClass() {...}
// this is an instance method
void MyClass() {...}
}
Perfectly legal. Probably shouldn't be, but is.
In your example, class1() is never getting called, because it's not a constructor. Instead, the default constructor is getting called.
Suggestion: familiarize yourself with Java naming conventions. Class names should start with uppercase.
The reason the constructor doesn't return a value is because it's not called directly by your code, it's called by the memory allocation and object initialization code in the run time.
Here is an article explaining this in greater detail:
https://www.quora.com/Why-is-the-return-type-of-constructor-not-void-while-the-return-type-of-a-function-can-be-void

Constructor with and without any statement

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;
}

Does using this() in Java create more recursive instances of an object?

If I have a constructor
public class Sample {
public static StackOverflowQuestion puzzled;
public static void main(String[] args) {
puzzled = new StackOverflowQuestion(4);
}
}
and inside the main method of a program i have
public class StackOverflowQuestion {
public StackOverflowQuestion(){
//does code
}
public StackOverflowQuestion(int a){
this();
}
}
Is this creating an instance of StackOverflowQuestion via constructor2 and then creating another instance of StackOverflowQuestion via constructor 1 and therefore i now have two instances of StackOverflowQuestion directly inside each other?
Or does constructor2 in this case kind of laterally adjust and then instead create an instance of StackOverflowQuestion via constructor1 ?
I think you mean:
public class StackOverflowQuestion
{
public StackOverflowQuestion(){ // constructor
//does code
}
public StackOverflowQuestion(int a){ // another constructor
this();
}
}
And call it like:
StackOverflowQuestion puzzled = new StackOverflowQuestion(4);
This will only create one object, because new is executed only once. The call this() will execute the code in the other constructor without creating a new object. The code in that constructor is able to modify the currently created instance.
It only creates one instance. One use case of it is to give default values for constructor parameters:
public class StackOverflowQuestion
{
public StackOverflowQuestion(int a) {
/* initialize something using a */
}
public StackOverflowQuestion() {
this(10); // Default: a = 10
}
}
this() is not the same as new StackOverflowQuestion()
this(5) is not the same as new StackOverflowQuestion(5)
this() and this(5) calls another constructor in the same class.
Therefore in this example:
public class StackOverflowQuestion
{
private int x;
private int y;
private int a;
public StackOverflowQuestion(){
this.x = 1;
this.y = 2;
}
public StackOverflowQuestion(int a){
this();
this.a = a;
}
}
The call to this() will just initialize the object and not create a new instance. Remember new StackOverflowQuestion(5) has been called already invoking the constructor which actually creates a new instance of the StackOverflowQuestion object
A constructor does not create an object. It just initializes the state of the object. It's the new operator which creates the object. Read through Creation of New Class Instance - JLS. Now what does this mean :
public class StackOverflowQuestion
{
public StackOverflowQuestion(){ // constructor
//does code
}
public StackOverflowQuestion(int a){ // another constructor
this();
}
}
StackOverflowQuestion puzzled = new StackOverflowQuestion(4);
A new object of StackOverflowQuestion is created by the new operator, just before a reference to the newly created object is returned as the result and assigned to the StackOverflowQuestion puzzled reference variable , the constructor StackOverflowQuestion(int a) makes a call to this() i.e. public StackOverflowQuestion(), code(if any) inside the default constructor runs and the control comes back to `StackOverflowQuestion(int a), the remaining code(if any) inside that is processed to initialize the new object.
The instance of a class is created at the moment you use the "new" operator. It is perfectly possible to create a class without constructors, because in that case, by default, the constructor with no parameters is available.
The "this" keyword just points to THIS specific object, so calling "this()" means "call my own constructor function, the one without parameters and execute what's inside"

Java: Access public member from a non-related class?

The following Java code is a stripped down example of the code I need. My question is, how do I access someInt from inside class Second? Note that Second implements another class, so I can not just pass someInt in.
package test1;
public class First {
public int someInt;
public static void main(String[] args) {
First x = new First();
}
public First(){
someInt = 9;
Second y = new Second();
}
}
class Second implements xyz{
public Second(){}
public void doSomething(){
someInt = 10; // On this line, the question lies.
System.out.println(someInt);
}
}
You can't access First's someInt field in Second because Second isn't an inner class of First. The changes below would fix your problem.
package test1;
public class First {
public int someInt;
public static void main(String[] args) {
First x = new First();
}
public First(){
someInt = 9;
Second y = new Second();
}
class Second {
public Second(){
someInt = 10;
System.out.println(someInt);
}
}
}
If you need to access the field in First (and not create a new one in Second), you need to pass a reference to the instance of First when you create the instance of Second.
Second y = new Second(this);
}
}
class Second {
public Second(First f){
f.someInt = 10;
In the terms of your question, "Access public member from a non-related class", the problem is solved by creating a relation. If that isn't allowed, this answer is wrong.
Accessing a public member follows the same syntax rules as accessing a public method (just without the brackets)
But having a public member in a class is usually not a good idea
The most direct way would be to
1) instantiate First
First f = new First()
2) access it directly because you made the instance variable someInt public
f.someInt = 10
A better way would be to provide accessors for someInt in First, and do it that way.
First f = new First();
f.setSomeInt( 10 );
...
int x = f.getSomeInt();
Within your second class, you must have a first class object. Create that object in your second class, then you will be able to access someInt.
You need to get a reference to an instance of First since someInt is not static.

Categories