Pass an object created in one class to another class - java

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

Related

How to use methods defined in anonymous class outside of it?

May I know how can I use/call the age method? Here is the Student class.
class Student {
public static void address(){
System.out.println("streetB");
}
}
public class School {
public static void main(String[] args) {
Student gg = new Student() {
public void age() {
System.out.println("9");
}
};
//how to call age() method here?
}
}
You are probably looking for something different, as you just created new class here that extends Student class, but it is anonymous so you can just access that new method as it does not belong to Student class.
If you are using java 10 then you can use var
class Student {
public static void address(){
System.out.println("streetB");
}
}
public class School {
public static void main(String[] args) {
var gg = new Student() {
public void age() {
System.out.println("9");
}
};
gg.age();
}
}
But that would be probably pretty bad idea, as there is just no reason to do such weird thing.
(var works here because it can represent that anonymous class at compile time)
You should probably add age field and method to Student class
Since gg is declared as Student and there is no age() method in that class, compiler will not allow you to call gg.age() because it is not guaranteed that every Student instance will be able to support it.
Pre java 10 solutions (if you are using Java 10 or later read this answer)
What you can try is reflection mechanism through which you can
gg.getClass() to get class literal representing actual type of object held by gg variable,
then getDeclaredMethod("age") to get age method declared in that class,
then invoke(gg) to call that method on object held by gg.
In short
gg.getClass().getDeclaredMethod("age").invoke(gg);
Other way would be not assigning created instance of anonymous class to any reference which would limit its possibility and call method directly on created object like
new Student() {
public void age() {
System.out.println("9");
}
}.age();
but this way we can't reuse that object anywhere later (because we don't have reference to it).

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();

Dynamically retrive the java object of Object class to a given class when class name is known

MyInterface.java
publc interface MyInterface{
void print();
}
Abc.java
public Class Abc implements MyInterface{
public void print(){
System.out.print("Inside Abc");
}
}
Xyz.java
public Class Xyz implements MyInterface{
public void print(){
System.out.print("Inside Xyz");
}
}
Main.java
public Class Main{
public static void main(String arg[]){
String classPath="Abc"; // this String will get assign # runtime.
Class<?> s = Class.forName(classPath);
}
}
Here inside main method classPath is "Abc", so i'm expecting Abc Instance.
The classsPath string will be Abc or Xyz or any Class Name that implements MyInterface.So depending the classPath String i want the instance of that class. like if ClassPath is "Abc" then Abc Class instance, ClassPath is "Xyz" then Xyz Class instance.
How can i achieve this dynamically.
You need to know what constructor to call.
Assuming all your classes have a no-argument constructor and you want that one:
MyInterface instance = (MyInterface) s.newInstance();
If the constructor has a different signature, you need to supply that, for example with a single String parameter:
MyInterface instance = (MyInterface) s
.getConstructor(String.class)
.newInstance("foo");
You can create an object dynamically at runtime using the name of the class, input as a simple string. This is done using a part of the Java language called reflection.
Reflection allows old code to call new code, without needing to recompile.
If a class has a no-argument constructor, then creating an object from its package-qualified class name (for example, "java.lang.Integer") is usually done using these methods:
Class.forName
Class.newInstance
If arguments need to be passed to the constructor, then these alternatives may be used instead:
Class.getConstructor
Constructor.newInstance
The most common use of reflection is to instantiate a class whose generic type is known at design-time, but whose specific implementation class is not. See the plugin topic for an example. Other uses of reflection are rather rare, and appear mostly in special-purpose programs.
I see a few typos in your post, so let's fix those first. public and class like
public interface MyInterface {
void print();
}
public class Abc implements MyInterface {
public void print() {
System.out.print("Inside Abc");
}
}
Then you use Class.newInstance() to create an Object, check that it's the expected type with instanceof and then cast like
public static void main(String[] args) {
try {
Class<?> cls = Class.forName("Abc");
Object o = cls.newInstance();
if (o instanceof MyInterface) {
MyInterface m = (MyInterface) o;
m.print();
}
} catch (Exception e) {
e.printStackTrace();
}
}
newInstance Method of Class is used to create new Instance.
public static void main(String arg[]){
String classPath="Abc"; // this String will get assign # runtime.
Class s = Class.forName(classPath);
Object object = s.newInstance();// to create new Instance
}

How do i get an object from another class in 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();"

Example of an instance method? (Java)

I'm still learning about methods in Java and was wondering how exactly you might use an instance method. I was thinking about something like this:
public void example(String random) {
}
However, I'm not sure if this is actually an instance method or some other type of method. Could someone help me out?
If it's not a static method then it's an instance method. It's either one or the other. So yes, your method,
public void example(String random) {
// this doesn't appear to do anything
}
is an example of an instance method.
Regarding
and was wondering how exactly you might use an instance method
You would create an instance of the class, an object, and then call the instance method on the instance. i.e.,
public class Foo {
public void bar() {
System.out.println("I'm an instance method");
}
}
which could be used like:
Foo foo = new Foo(); // create an instance
foo.bar(); // call method on it
class InstanceMethod
{
public static void main(String [] args){
InstanceMethod obj = new InstanceMethod();// because that method we wrote is instance we will write an object to call it
System.out.println(obj.sum(3,2));
}
int f;
public double sum(int x,int y){// this method is instance method because we dont write static
f = x+y;
return f;
}
}
*An instance method * is a method is associated with objects, each instance method is called with a hidden argument that refers to the current object.
for example on an instance method :
public void myMethod {
// to do when call code
}
Instance method means the object of your class must be created to access the method. On the other hand, for static methods, as its a property of Class and not that of its object/instance, it is accessed without creating any instance of the class. But remember static methods can only access static variables, where as instance method can access the instance variables of your class.
Static methods and static variables are useful for memory management as it does not require to declare objects which would otherwise occupy memory.
Example of instance method and variable :
public class Example {
int a = 10; // instance variable
private static int b = 10; // static variable (belongs to the class)
public void instanceMethod(){
a =a + 10;
}
public static void staticMethod(){
b = b + 10;
}
}
void main(){
Example exmp = new Example();
exmp.instanceMethod(); // right
exmp.staticMethod(); // wrong..error..
// from here static variable and method cant be accessed.
}
Instance methods are the methods that require an object to access them where as static methods do not. The method that you mentioned is an instance method since it does not contain static keyword.
Example of instance method:
class main
{
public void instanceMethod()//instance method
{
System.out.println("Hello world");
}
}
The above method can be accessed with an object:
main obj=new main();//instance of class "main"
obj.instanceMethod();//accessing instance method using object
Hope this might help you.
Instance block with Cases { Static , constructor , Local method )
OutPut will be :

Categories

Resources