if i want to call multiple methods of a one class from another class can i call them by using only 'new classname()' without catching it in class reference?
public class Example {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
new pqr().a=5;
new pqr().b=10;
new pqr().display();
}
}
class pqr
{
int a,b;
public void display()
{
System.out.println(a+" "+b);
}
}
This creates three new objects. Not just one.
new pqr().a=5;
new pqr().b=10;
new pqr().display();
One object with a = 5 and another with b = 10.
Remember you are not working with one object.
Whenever you use new keyword. JVM creates a new object.
if i want to call multiple methods of a one class from another class can i call them by using only 'new classname()' without catching it in class reference?
It's not clear what you mean by "catching it" but you are using a reference... you're just not assigning it to a variable.
In your example, you're creating three different objects - the calculation on your final line just prints 0, because you've only set a and b in other objects. If you want to use a single object for multiple operations, you'll either need to store the reference in a variable, or those operations will have to return "this", allowing you to chain method calls together:
class Sample {
private int a,b;
public void display() {
System.out.println(a+" "+b);
}
public Sample setA(int a) {
this.a = a;
return this;
}
public Sample setB(int b) {
this.b = b;
return this;
}
}
...
new Sample().setA(5).setB(10).display();
This sort of chaining for setters is common in the builder pattern.
You can use the Builder pattern if you want something like that:
NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8).
calories(100).sodium(35).carbohydrate(27).build();
The builder pattern is one possibility. The another one is to have static properties so all object will share it's values.
static int a,b;
Related
public class Main {
void sum(int a, int b) {
System.out.println((a + b));
Main ob = new Main();
ob.difference(200, 100);
}
void difference(int a, int b) {
System.out.println((a - b));
}
public static void main(String args[]) {
Main ob = new Main();
ob.sum(100, 25);
}
}
When I create objects of same name in the main method, compiler is throwing error but when I create objects with same name in different methods it is getting compiled. Why is it so?
You can reuse the reference to make the variable point to a new object like below.
In this case, you don't have to declare the type again. It will always be the same type for the same variable, that's how statically-typed languages work.
public static void main(String args[]) {
Main ob = new Main(1);
ob.sum(100, 25);
ob = new Main(2);
ob.sum(100, 25);
}
Yes, #ernest_k is right on point.. but I am not sure why you need another object inside add method, methods of inside a class can call each other without an object, since Main was a static method while add and subtract are not, you needed an object inside your main method.
You can have one single object inside main and add will be called using that which in turn difference.
Note: You can also make add and difference as static so you do not need any object at all.
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
I wonder if there is any way that I can declare a new instance with parameters, do not fill them, and just set them later.
Here is an example:
private Example example = new Example() // Need 1 parameter.
public void foo(Object arg1)
{
example = new Example(arg1);
}
It is clear that this is not possible, but is there a way to do something similar to that?
You can always use a parameter-less constructor, and then set the properties of the created instance later.
....
public Example ()
{
this.s = null;
}
public Example (String s)
{
this.s = s;
}
....
public void setS (String s)
{
this.s = s;
}
....
Example ex = new Example ("something");
Example ex2 = new Example ();
ex2.setS("Something Else");
public class Example{
private Object object1;
public Example(){
}
public void setObject1(Object o){
this.object1 = o;
}
}
Now you can use this as follows:
Example example = new Example();
example.setObject1(someObject);
As noted by others and yourself already, there is no easy / official way of object construction when you can't provide the parameters needed.
You may want to look at the Objenesis project. They provide clever ways of instantiation of objects in non-standard ways. To my knowledge sometimes being able to instantiate objects without providing the usually mandatory arguments declared by the constructors.
I've been looking for the answer to this problem all day.
I have a value class that holds a variety of values as long as the program is running.
I create a new Value object in class A, and store an int value.
Class A also has a printMoney() method.
public class A {
Value value = new Value();
value.setMoney(100);
public void printMoney {
System.out.println(value.getMoney);
}
In class B, I want to be able to call printMoney() from class A, so logically I do the following:
public class B {
A a = new A();
a.printMoney();
}
This does, however, return '0' as a value instead of '100'.
I understand that by creating an A object, I automatically create a new value object, which has its default money value. So, basically my question is; how do I solve this?
Make the object static. static Value value = new Value();
static variables are shared across all the objects
So the change made in static variable will be reflected for all the objects of class.
if you want to get that value in A you have to assign the value in A construtor, like
public class A {
Value value = new Value();
public A() {
this.value.setMoney(100);
}
otherwise, you can make the value static
you should receive the instance that creates the object B and save it then you would be able to call it
like so:
public class A {
B b = new B(this);
}
public class B {
A a;
public B(A a) {
this.a = a;
}
private someMethod () {
a.printMoney();
}
}
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"