How do i get an object from another class in java - java

i have an object for example called myObject and this object has an integer which is 5. How would i send this object to another class or retrieve the object from its class it was created in so i can use the object and all its values even though i created in a different class?
the class myObject was created from
public class Class
{
int Int;
public void setInt(i)
{
Int = i;
}
}
how would i send the object below to another class where i can use it and have access to all its values etc.
Class myObject = new Class();
myObject.setInt(5);

Your variables should be more specific. Having an int named 'Int' and class named 'Class' can get very confusing.
Your second class is going to need to take the first class as a value in the constructor, unless you're going to make everything in the first class visible to everything in the package or the project (which I wouldn't recommend doing). Therefore, we need a public getter and setter for the int value in the original class (now named TestObject; and the int now called num), because I made the variable private (visible only to the class). Now that the getters and setters are created, the second class (now named TestObject2) can call the getter from TestObject to retrieve the int value.
It's kind of counterproductive to have a getter for the value in TestObject, but I just included it to show you how to get the value.
If you have any questions let me know! I put the code below:
public class TestObject{
private int num;
public int getInt(){
return num;
}
public void setInt(int num){
this.num = num;
}
public static void main (String[] args){
TestObject obj = new TestObject();
obj.setInt(5);
TestObject2 obj2 = new TestObject2(obj);
System.out.println(obj2.getTestObjectNum());
}
}
public class TestObject2 {
TestObject testObject;
public TestObject2(TestObject testObject){
this.testObject = testObject;
}
int getTestObjectNum(){
return testObject.getInt();
}
}

define the class so your class would recognize it then call it from within the class like this:
newClass = new Class();
newClass.setInt(x);
if it is in another package i believe it is something like this:
newClass = new packageName.Class();
newClass.setInt(x);
this is exactly how imports work, you define the class by "import javax.swing.JFrame;
then call anything inside that class by defining an object like "JFrame f = new JFrame();
then you call the methods inside the JFrame class by doing "f.add();"

Related

How to use variables declared in another class?

If I have declared an int variable called impart and declared it in class A, and then I want to call it in class B and display it there. How would I go about doing that? I have heard you can do it by using the reserved keyword 'import', can somebody show me that way?
If you make the variable Public such as
public int potato = 15; Than that can be called in any class.
Or if you want your code to be better declare a private variable then create a method to return said variable.
public class a
{
b wow = new b();
wow.getPotato();
}
public class b
{
private potato;
public b()
{
//You dont neccessarily need this as there is a default constructor
}
public int getPotato()
return potato;
}
you will need to do something like this:
public class A {
// you still have to set a value for i
private int i;
public int getI() {
return i;
}
public class B {
public static void main(String[] args) {
A a = new A();
// now you can use the value with
a.getI();
}
}
you could also set the variable public and access it directly (or make A static as well as the variable, then you can access it without instantiating A) but this is bad coding practice
You create a Object of that Class and then call the getter method for the variable.
A aclass = new A();
aclass.getImport();
If you make the variable static, you can use int b = A.impart;. Making the variable static allows you to cross it over to another class without having to get a reference to the class.

A static method belongs to the class rather than object of a class

A static method belongs to the class rather than object of a class.
A static method can be invoked without the need for creating an instance of a class. What does it mean?
It means that, rather than needing to create a new instance from the class and then calling the function like:
Foo f = new Foo();
f.bar();
you can instead access it directly from the class like:
Foo.bar();
That obviously means that you can't use any non-static field or method of the object from a static method, of course.
ClassObject classObj = new ClassObject();
classObj.doSomething();
vs.
ExampleClass.staticMethod();
First one needs an instance of ClassObject to call doSomething(). The second one doesn't.
Here is an example of a class with a static method and standard method.
public class MyClass {
public static void staticPrintMe() {
System.out.println("I can be printed without any instantiation of MyClass class");
}
public void nonStaticPrintMe() {
System.out.println("I can be printed only from an object of type MyClass");
}
}
And here is the code to call both methods:
MyClass.staticPrintMe(); // Called without instantiating MyClass
MyClass myClassInstance = new MyClass(); // MyClass instantiation
myClass.nonStaticPrintMe(); // Called on object of type MyClass
As you can see the static method is invoked without any object of type MyClass.
Take the java.lang.Math class as an example. In this line of code:
double pi = 2 * Math.asin(1);
I've referred to the Math class, but the asin method is static. There's no instance of the class created, the class just acts as a placeholder for this utility function.
A corollary of this is that a static method may not access any per-instance data - it can only access class variables that are also declared static.
Look at this example. Defining a class with both an static method and an instance method:
public class MyClass {
public MyClass() {
// do something
}
public static staticMethod() {
// do something
}
public void instanceMethod() {
// do something
}
}
Usage:
MyClass anInstance = new MyClass();
// static method:
MyClass.staticMethod();
// instance method:
anInstance.instanceMethod();
// this is possible thought discoraged:
anInstance.staticMethod();
// this is forbidden:
MyClass.instanceMethod();
To invoke static method you do not need to build a class instance (i.e object).
For example:
class Multiplier {
public static double multiply(double arg1, double arg2) {
return arg1 * arg2;
}
}
static method does not use class instance information, and you can use the method as:
Multiplier.multiply(x, y);
non-static method uses class instance information and depends on it.
for example:
class Pony {
private Color color;
private String name;
public Pony(Color color, String Name) {
this.color = color;
this.name = name;
}
public void printPonyInfo() {
System.out.println("Name: " + this.name);
System.out.println("Color: " + this.color);
}
}
Pony pony1 = new Pony(Color.PINK, "Sugar");
Pony pony2 = new Pony(Color.BLACK, "Jupiter");
and when you call:
pony1.printPonyInfo();
pony2.printPonyInfo();
You get name and color for every pony object. You cannot call Pony.printPonyInfo() because printPonyInfo() does not know, what to print. It is not static. Only when you have created Pony class instance, you can call this method, that depends on the class instance information.
When we call a method, we need an instace of a class like this.
class SomeClass {
public void test() {}
}
SomeClass obj = new SomeClass();
obj.test();
'obj' is an instance of SomeClass.
Without an instance like 'obj', we can't call the test method.
But the static method is different.
class SomeClass2 {
public static void testStatic() {}
}
We don't call the testStatic method like above case of SomeClass.
SomeClass2 obj = new SomeClass2();
obj.testStatic(); // wrong
We just call with only class type.
SomeClass2.testStatic();

Java transferring variables from a super class to the sub class

In java i have a class A which extends class B
I want to assign all of the contents from class B to class A
thing is i want to do it from inside class A now this seems reasonable easy to do just transfer all of the variables.
This is the hard part. I didn't make class B it's a part of android.widget
In c++ you would just take in class b and then assign to *this and cast it.
How would i go about doing this in java?
To further clarify it's a relativelayout i need to copy all the contents of a relativelayout into a class that extends relative layout
class something extends other
{
public something(other a){
//transfer all of the other class into something
this=(something)a; // obviously doesn't work
//*this doesn't exist?
//too many variables to transfer manually
}
}
Thanks so much for all the help. Really appreciate it!!!
See the code given below . It is using java.lang.reflect package to extract out all the fields from super class and assigning the obtained value to the child class variables.
import java.lang.reflect.Field;
class Super
{
public int a ;
public String name;
Super(){}
Super(int a, String name)
{
this.a = a;
this.name = name;
}
}
class Child extends Super
{
public Child(Super other)
{
try{
Class clazz = Super.class;
Field[] fields = clazz.getFields();//Gives all declared public fields and inherited public fields of Super class
for ( Field field : fields )
{
Class type = field.getType();
Object obj = field.get(other);
this.getClass().getField(field.getName()).set(this,obj);
}
}catch(Exception ex){ex.printStackTrace();}
}
public static void main(String st[])
{
Super ss = new Super(19,"Michael");
Child ch = new Child(ss);
System.out.println("ch.a="+ch.a+" , ch.name="+ch.name);
}
}
All the variable and function of parent class(not private) is direct access in child class.You don't need to assign any thing in child Class.You can direct access.
This will not work:
Something something = (Something) other.clone();
if the true runtime type of other is Other.
Instead you have to create a copy constructor, or instantiate other as an instance of Something and then clone it.

Pass an object created in one class to another class

I have a class named StatisticFrame. This class creates an object named stats inside a method. How can I pass this object created from StatisticFrame class to another class?
Keep a variable that will point to the receiver object (say of type TargetFrame class) in your StatisticFrame class and then invoke the method (say SetStatsObject(object obj)) defined in the receiver object to receive the object.
your StaticFrame class will look like this
class StatisticFrame {
private TargetFrame targetObject = null;
public StatisticFrame (TargetFrame obj) {
this.targetObject = obj;
}
public void Send (Object stats) {
object stats = GetStatsObject(); // this will create and returns stats object
targetObject.SetStatsObject(stats);
}
//...
}
and your TargetFrame (the receiving object's class) should look like this
class TargetFrame {
public void SetStatsObject(Object stats) {
// Do what ever you want with stats
}
// .....rest of the methods follows
}
You can pass the created object as argument to another class constructor or it's method.
class Apples{
public static void main(String[] args){
ApplesTestDrive obj = new ApplesTestDrive();
ApplesSampleTestDrive objOne = new ApplesSampleTestDrive();
// Pass created object obj as argument to ApplesSampleTestDrive method.
objOne.paint(obj);
}
}
class ApplesTestDrive{
public String bucket;
public ApplesTestDrive(){
bucket = "blue";
}
}
class ApplesSampleTestDrive{
public void paint(ApplesTestDrive obj){
System.out.println("Paint apple one: " + obj.bucket);
}
}
Another class needs a method as an argument that expects your stats object and call that method from your class and pass your stats object
private void yourmethod(){
Stats stas =
AnotherClass ac = new AnotherClass();
ac.thatMethod(stats);
}
class AnotherClass {
public void thatMethod(Stats stats){
}
}
One of ways is that you can create method in your "another class" that will accept as argument object you want to pass, and you call that method from your base class
class Sender{
public void createAndSend(Reciever reciver){
String s="some data from Producer";
reciver.recieve(s);
}
}
class Reciever{
public void recieve(String data){
System.out.println("I recieved "+data);
}
}
//lets test it
class TestX{
public static void main(String[] args) {
Sender s=new Sender();
Reciever r=new Reciever();
s.createAndSend(r);
}
}
output: I recieved some data from Producer
There are number of ways you can achieve this . either make the return type of method as stats and then in other class you can make object of StatisticFrame and call that method.
StatisticFrame sf=new StatisticFrame();
Stats st=sf.method();
Other way if you don't want to make return type as Stats then Make global private variable of type Stats and assign this in your method, and then one public getter method will return this object to other classes.
You can create an object for the other class that you want to pass the object with the constructor that accepts your newly created object.
Another way you can use some callback functions using interface
One way :-
Suppose you have one class Xyz
The object that you want make the getter method for it and in another class Abc make the object of Xyz and with that object call the getter method and store the return of it in your current class
2nd way :-
use inheritance make the class as super
class Abc extends Xyz
By this u will directly gets access to all the objects, methods present in super class
Hope that this make sense to you

Using variable in different file

I have two separate programs in java, and I have saved them in two different files. I want to use a variable (which is in the first program) in the second program.
How to do this?
Depends what you mean by "want to use a variable in another program". How are you defining your variables? The two "programs" must be two separate classes, so you'll be defining a variable as a class member, most likely. So, in you first class, you could have something like
public class ClassA {
public int variable;
...
}
and then in your second class you coul access it like so:
public class ClassB {
public ClassB() {
int var = new ClassA().variable;
}
}
Depending on how you define that variable (public/private/protected and static/instance), the way to access it would be different.
I am going to assume a few things here. The first assumption is that you are trying to access a variable in a different class and the second assumption is that those classes are in the same package most likely the default package. So to access a variable in class A from class B you need to instantiate class A.
ClassA.java
public class ClassA{
public int mMyInt = 10;
}
ClassB.java
public class ClassB{
public ClassB(){
ClassA myClass = new ClassA();
System.out.println(myClass.mMyInt);
}
public static void main(String args[]){
ClassB app = new ClassB();
}
}
I hope this helps.

Categories

Resources