Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

hey im struggling with a concept maybe you can explain it to me, or point me in

ID: 670052 • Letter: H

Question

hey im struggling with a concept maybe you can explain it to me, or point me in the right direction..
I dont understand when objects are used as variable types and how they can be used. ill give you and example..
in class 1 im calling as a reference type class2 as"answer"- now how do i use that in main, and
what does all that mean ? thanks

public class class2
{
int num1;
int num2;
class2(int num1, int num2)
{
this.num1 = num1;
this.num2 = num2;
}

}

public class class1
{
class2 numbers;
int answer;
class1(int answers, class2 numbers)
{
this.answer = answers;
this.numbers = numbers;
}

  
}
public static void main(String[] args)
{
class2 class2= new class2(2,3);
class1 class1 = new class1(2,class2);
System.out.println(class1);

  

  
}

Explanation / Answer

A class name is used to declare objects of that type. Basically what happens is, when you create a class you basically create a new user defined data type. To create variables of that data type you need objects. Once you create an object of the class you want to access you are basically done. With the help of that object you can access both data members or methods of that class type. The first problem that i see in your code is that the main method doesn't belong to either of the class. This approach is wrong. If you need a starting point to your code it has to be you main methoed which in turn should have it's definition in a particular class. Coming to your question of accessing numbers and not answer which is a reference to class2, the reference that you create can copy values of data members into the variables you create in class1 using the dot operator. This might sound confusing so here is a sample code to show you how it's done. This can be written within the definition of class1 :

class2 numbers=new class2();

numbers.num1=answers;

What the above code does is first create an object of type class2 and then access data members from class two and initialize them to values which are being sent when the object of class1 gets create once the main method starts compiling. Hope you understand the concept.

For further readings related to your query you can also give a read or have a look at the following:

1. Java complete reference (Herbert Schildt) Chapter 6 (introducing classes) Topic: Declaring Objects

2. A few useful youtube links are : https://www.youtube.com/watch?v=4XRy-TdfU0I

https://www.youtube.com/watch?v=M8pv52yV0rM