I need to pass an argument between two classes in different packages.
For example, I have an int a in class A in package AA.. I need to pass it to class B in package BB which will change the value of a and pass it back to class A.
Either Use fully qualified class name or import it in another program . E.g if you want to create an object of class A which is in AA package in class B which is in different package, use
AA.A obj = new AA.A();
Now call the method which you want to pass value to, using this obj reference variable.
The above code did not work for me. I had to change the import in package B to make it work.
package BB;
import AA.A;
public class B {
public int change_a(int a){
return a+1;
}
}
You should be passing arguments like this
package AA;
import BB.B;
public class A {
int a = 5;
private void play() {
B b = new B();
// Here we are passing the int argument to a method in different class and different package
int new_a = b.change_a(a);
System.out.println("a after the change is "+ new_a);
}
public static void main(String[] args){
new A().play();
}
}
And your class B
package BB;
import BB.A;
public class B {
public int change_a(int a){
return a+1;
}
}
Related
Long story short, I cannot figure out why this code doesn't work.
import java.util.*;
class sup{
int a;
sup(){
a = 1;
}
}
class subB extends sup{
int b;
subB(){
b = 2;
}
}
class subC extends sup{
int c;
subC(){
c = 3;
}
}
public class runMain{
public static void main(String args[]){
List<Object> classes = new ArrayList<Object>();
classes.add(new sup());
classes.add(new subB());
classes.add(new subC());
System.out.println(classes.get(0).a); //should print 1
System.out.println(classes.get(1).b); //should print 2
System.out.println(classes.get(2).c); //should print 3
}
}
As stated in the comment, I am wanting the last 3 lines to print the values of a, b and c in the different classes. When instead having e.g.
System.out.println(classes.get(0));
it prints sup#6d06d69c, which I assume is just the class name "#" the memory location, so everything else in the program seems to be working as intended.
Benefits of Inheritance include code re-use, and method overloading - neither of which your code is exploiting. In your case it may either be:
Re-use: of the super-class variable a, in which case the sub-classes would not have their own variables b and c, but rather assign their respective values to the super-class declaration of a, assuming it is either public or protected. Better coding style would include a shared getter method in the super class.
Method overload: Each of the three classes would have a commonly-named method that returns their respective values.
In this example, the three classes involved in the inheritance share a variable, and a getter:
import java.util.ArrayList;
public class MyClass{
static class sup{
protected int a;
sup(){
a = 1;
}
public int a() {
return a;
}
}
static class subB extends sup{
subB(){
a = 2;
}
}
static class subC extends sup{
subC(){
a = 3;
}
}
public static void main(String[] args) {
ArrayList<sup> classes = new ArrayList<sup>();
classes.add(new sup());
classes.add(new subB());
classes.add(new subC());
System.out.println(classes.get(0).a());
System.out.println(classes.get(1).a());
System.out.println(classes.get(2).a());
}
}
I would like to know how the default package is defined in Java.I know how public and private access is defined but I don't know whether there is any default package access that is defined in package level access in java.
The code I tried to execute is:
class A
{
public static void value()
{
int a;
a=5;
}
public static void main()
{
value();
}
}
class B
{
public void greet()
{
System.out.println("Value of a is"+a);
}
}
The error I got is:
D:\Downloads\pro>javac A.java
A.java:17: error: cannot find symbol
System.out.println("Value of a is"+a);
^
symbol: variable a
location: class B
1 error
Since both classes belong to the same default package shouldn't class B access class A's members(a)?
I'm asking this question because when I compile java file containing two classes since no modifier is given for classes,java compiler would give package level access as the default access modifier for the classes.Since no package is defined,java compiler would use the default package but I couldn't get whether the default package is included in package level access in java.Could anyone help me.
a is a variable inside the static function value and not visible outside of that function at all. Doesn't have to do with access specifiers.
The default package is the package without a name, all classes without a package declaration at the top of the file fall into it.
It is subject to all normal rules of packages except that you can't reference classes of it from a class inside a package.
For example I have 2 java files:
public class A{
public static void foo(){System.out.println("fooCalled");}
}
and
package com.example;
public class B{
public static void main(String[] arg){
A.foo();//won't compile
}
}
Then B (or in the qualified form com.example.B) can never call the foo of A without reflection magic.
Your program has nothing to do with access specifiers, as you have declared your variable int a inside a method.
Thus it becomes just a local variable. You cannot even use it outside this method in the same class.
If we talk specifically about access specifiers then we can have default access specifier in Java which has scope up to the same package only.
package com;
class A{
int a; // this is an instance variable
static int b; //this is a class variable
}
package com;
class B{
//can use a variable here
// To use a here, we need new A().a;
// To use b here, we can do, A.b
}
package hello;
class C{
//can't use a variable here
}
Edit
Suppose we create a file with name MyProgram.java on Desktop. Below is the code of this file,
class First{
int a; // a is an instance variable
static int b; // b is a static (class) variable
void display(){
int c; // c is a local variable
}
}
class Second{
public static void mian(){
First obj = new First();
obj.a = 10; // to access instance variable we need object of the class
obj.b = 20; // class variable can also be accessed using the object
// First.a = 10; //It won't work as a is instance variable and can be accessed by object only
// First.b = 20; // We can also access static variables by class name directly without using any object
// obj.c = 30; // It won't work. As c is a local variable of method display and can be used only inside that method.
// First.c = 30; //It also won't work as c can only be used inside the method where it is declared.
}
}
So finally I got how we could access an variable in another class without creating an object provided both classes rest in the same package.Just make the variable static.
Here's the code:
import java.io.*;
class A
{
static int a=5;
public void turn()
{
System.out.println("value of a is"+a);
}
}
class B
{
public static void main(String args[])
{
int b;
b=A.a;
System.out.println("value of a is"+b);
}
}
This shows that classes residing in the same package can access each other's members provided it is static even though it is not public because default package access comes to play.
Default access modifier means we do not explicitly declare an access modifier for a class, field,
method, etc.
A variable or method declared without any access control modifier is available to any other
class in the same package. The fields in an interface are implicitly public static final and
the methods in an interface are by default public.
In your class B, a is not defined.
class B {
public void greet() {
System.out.println("Value of a is" + a );//cannot find `a` inside `B`
}
}
Now coming to accessibility, since your both classes are in same package B class can access public, protected and default(no access modifiers) members of other class like A. But in your case a is a local variable inside the A member method value(), so a variable cannot be accessed outside the method where it was declared.
class A {
public static void value() {
int a;//not accessible outside this method
a=5;
}
public static void main() {//FYI: this main is not valid to execute your code, missing here: `String[] args` argument
value();
//`a`, is even not accessible here, forget about class `B`
}
}
Sample code, all are in same package:
class A {
String bar;
}
class B {
public foo() {
A a = new A();//required, as `bar` is instance(non-static) member of class `A`
a.bar 'hi there';//set value
System.out.printf("a.bar = %s\n", a.bar);
}
}
EDIT
Sample code with nested class:
class A {
int foo;
class B {
void setFoo() {
foo = 45; //accessing member of class `A`
}
}
}
Working code:
<pre>
<code>
class A {
private int foo;
private B b;
A() {
foo = -1;
b = new B();
}
class B {
void setFoo(int foo) {
System.out.printf("Inside B's setFoo(), foo = %d\n", foo);
A.this.foo = foo; //accessing member of class `A`
}
}
int getFoo() {
return foo;
}
public void setFoo(int foo) {
System.out.printf("Inside A's setFoo(), foo = %d\n", foo);
b.setFoo(foo);
}
}
class Ideone{
public static void main (String[] args) {
A a = new A();
System.out.printf("main(), foo = %d\n", a.getFoo());
a.setFoo(34);
System.out.printf("main(), foo = %d\n", a.getFoo());
}
}
</code>
</pre>
In one directory, I have defined the following file A.java:
package test;
public class A {}
class B {
public void hello() {
System.out.println("Hello World");
}
}
From a different directory, if I do the following:
import test.B;
public class X {
public static void main(String [] args) {
B b = new B();
b.hello();
}
}
and compile javac X.java, I get the following error:
X.java:2: test.B is not public in test; cannot be accessed from outside package
import test.B;
^
X.java:7: test.B is not public in test; cannot be accessed from outside package
B b = new B();
^
X.java:7: test.B is not public in test; cannot be accessed from outside package
B b = new B();
^
I cannot change the sources in package test. How do I resolve this?
In Java, there are 4 different scope accessibilities:
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
In your case, B has no modifier, which means it can be seen inside the class and inside the package only. Therefore, if you create class X that is an other package, it won't see B.
To acess B, you need to define a class that is inside the same package as B which in your case is the package test.
Default access modifier OR no modifier specified member is only accessible in declared package but not outside the package.So in your case B is only accessible inside package named test. Read more on Access Modifiers.
If you cannot change the sources in package test.Than move your code/class to test package.
Use reflection:
package test2;
public class Main {
public static void main(String[] args) throws Exception {
java.lang.reflect.Constructor<?> bConstructor = Class.forName("test.B").getConstructor(/* parameter types */);
bConstructor.setAccessible(true);
Object b = bConstructor.newInstance(/* parameters */);
java.lang.reflect.Method hello = b.getClass().getMethod("hello");
hello.setAccessible(true);
hello.invoke(b);
}
}
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();"
In Java, is there any way to use the JDK libraries to discover the private classes implemented within another class? Or do I need so use something like asm?
Class.getDeclaredClasses() is the answer.
I think this is what you're after: Class.getClasses().
package com.test;
public class A {
public String str;
public class B {
private int i;
}
}
package com.test;
import junit.framework.TestCase;
public class ReflectAB extends TestCase {
public void testAccessToOuterClass() throws Exception {
final A a = new A();
final A.B b = a.new B();
final Class[] parent = A.class.getClasses();
assertEquals("com.test.A$B", parent[0].getName());
assertEquals("i" , parent[0].getDeclaredFields()[0].getName());
assertEquals("int",parent[0].getDeclaredFields()[0].getType().getName());
//assertSame(a, a2);
}
}