When creating a method inside a class if you use the parameter:
public String Method(ClassName NewObject){}
or in my example below:
public String EqualsTo(Deck aCard){}
will it create a new object of that class within that method? If not anyone mind explaing what I is happening with that parameter?
NOTE: Disregard any minor syntax errors as I just constructed this to get my question across better so this is not a complete class.
import java.util.Scanner;
import java.util.Random;
public class Deck {
private int suit;
private int rank;
private Random generator = new Random();
Scanner in = new Scanner(System.in);
//Default constructor
public Deck() {
suit = suit.random(4);
rank = rank.random(13);
}
public String EqualsTo(Deck aCard){}
}
Objects are created when you use the new keyword. On the other hand, when you declare a method as
public String EqualsTo(Deck aCard){}
it says that the EqualsTo() method takes a Deck reference as a parameter. In order to use the method, you need to create a Deck object and keep a reference to it. Then you send the reference to the method.
That parameter act as a place holder for that type of object. It doesn't actually create it, the method signature says:
I'm an EqualsTo() method and I take/require a Deck type of instance/object as a parameter.
It return a String as a result.
By the way, I recommend using a boolean as the return type instead of a 'String' for an EqualsTo method.
Fundamental thing: Java is pass by value.
A new object is not created.
Object reference value created by the calling entity is copied to the method argument aCard.
Any modifications done on this object will remain visible to the calling entity. This is because the reference value is pointing to the same address location of the object.
Here's an example.
public class Test2 {
public int bla;
public static void main(String[] args) {
Test2 test = new Test2();
test.bla = 878;
test.doSome(test); // Calling Location
System.out.println(test.bla);
}
public void doSome(Test2 test) {
test.bla = 95;
}
}
NO
public String EqualsTo(Deck aCard){}
Does not create a new object when it is called.
Here is where the objects are created. Use case
Deck deck1 = new Deck(); // NEW OBJECT CREATED
Deck deck2 = new Deck(); // NEW OBJECT CREATED
String result = deck1.EqualsTo(deck2); // NO NEW OBJECT CREATED,
// JUST PASSED REFERENCE OF EXISTING OBJECT
// (except the result of course, which is probably a new object)
Related
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 am facing problems while trying to implement 2 linked lists in my Java code.
If I declare my "head" variables in main and pass them to any function, they could not be modified by that function as the referencing variable would be local to that function.
But if I make them class variables, the called function could not know which of the 2 "head" variables I am referring to.
This problem could be easily solved in C language by passing double pointers in functions so that the local variable can modify the passed variable but how to solve this problem in Java? Thanks.
Pointers aren’t used in Java
Defines the attribute at the class level and don't use it in the signature of your methods, or return the value of your function to the original variable.
public class MyClass{
private string value;
public myFunction(){
value = toto; // this will change the value of the attribute directly
}
public static void main(String[] args) {
MyClass myClass = new MyClass();
myClass.myFunction(); // The new value is saved at the class level
}
}
or
public class MyClass{
public String myFunction(String value){
value = "toto";
return value; // The value modified is return back to the caller
}
public static void main(String[] args) {
MyClass myClass = new MyClass();
String myValue = myClass.myFunction(myvalue); // The new value is saved
}
}
I want to set the value of the next array object whenever an object is created in my main function.
This is the object
public class MyObject{
private int objCount = 0;
private int i = 0;
public class Property{..}
public Property propertyArray[] = new Property[12];
}
Main function creates an empty object and adds properties to the property array.
The object needs to keep different number of properties.
MyObject foo = new MyObject();
foo.add("ID", 2);
foo.add("MIE",132);
MyObject bar = new MyObject();
bar.add("REV", 22);
There is also an array of the object,
public MyObject[] ObjectArray = new MyObject[5];
I want to call a method that increases the object array index when a new object is created
Yes, Java makes a call when a new object is created, except it's not calling a method, it is calling a constructor. Constructors are declared like methods with no result type, and the name matching the name of the type, i.e. like this:
public class MyObject {
private int objCount = 0;
private int i = 0;
public class Property{..}
public Property propertyArray[] = new Property[12];
// This is the constructor
public MyObject() {
... // <<== Do stuff here
}
}
If you would like to add items to an array inside the MyObject class constructor, the array needs to be static: although constructors can access instance variables, each constructor gets a brand-new set of instance variables with which to work.
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"
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;