Classes using each other in packages
I've almost understood package's mechanic. But when I try to use class which is defined in another file in a package I've got an error :/. I have CLASSPATH set to .;.
Here is sample code:
File Main.java
package testpackage;
public class Main {
public static void main(String args[]) {
JLogin login = new JLogin();
login.setSize(250,100);
login.setVisible(true);
}File JLogin.java starts with package testpackage; too and contains public class JLogin.
When I dont use package (only default packages), everything is ok.
But when I move Main.java to upper directory and write import testpackage.JLogin; instead of package word everything is ok.
Thx in advance
Which files are in which directories?
What's your classpath?
What command are you using to compile/run?
What is the error you're getting?
Similar Messages
-
Compiling simultaneously two classes referencing each other
Hi,
When we want to compile 2 classes simultaneously in a package, we give command --
javac package-name/*.java
Suppose the two classes are ClassA and ClassB and ClassA has a reference of ClassB. So the compiler will finish compiling ClassB before compiling ClassA.
But, if both the classes have each others' reference, how does compiler resolve this? Because, even in that case both classes get compiled
Regards,
AmitLets say that compilation is done in 2 steps.
The first step is done for all files first.
Then the second step is done for all files.
That means that for the second step the compile-time resolution has takes place.
Two classes that refers to each other must go through the first step in
the same compilation so that in the second step when
they are referring to each other they are easily resolved.
This is different from runtime resolution. -
Problems with classes referencing each other...
I've got a problem....i have a program with two classes, and each class needs access to methods stored in the other class.
I've tried to create a reference (Classname name=new Classname();), but upon execution, i get a Exception in thread "main" java.lang.StackOverflowError, and a long list of locations, all pointing to the references i created at the top of each class.
What's wrong, and how do I fix this?You have infinite recursion. A method or constructor is calling itself, or is calling another method or constructor that eventually ends up calling the first one.
If you can't find it, post code. Use [code] and [/code] tags, which you can get with the code button, to make the code readable. -
Classes which inherited from the same abstract class calling each other
I have a design that contains such classes.
1) Media - defines some methods to get data which business logic wants and some others to deal with data
media.java
public abstract class Media {
public abstract Object getSomeData(String type);
public void methodForMedia() {
// do something here...
}And certainly, a lot of classes derive from it to function differently.
etc,
DynamicMedia.java
public class DynamicMedia extends Media {
public Object getSomeData(String type) {
// get some data here...
return somedata;
public void methodForMedia() {
// inherits and overrides here
public void methodForDynamicMedia(String data1, Object data2) {
// do something here...
}FixedMedia.java
public class FixedMedia extends Media {
public Object getSomeData(String type) {
// get some data here...
return somedata;
public void methodForMedia() {
// inherits and overrides here
public Object getFixedMediaData(String type) {
// get some fixed data here
return someFixedData;
}2) Business - which implements business logic
public class Business {
public void transactionOne() {
FixedMedia fm = getMedia(FixedMedia.class);
Object fixedData = fm.getFixedMediaData("fixedDataType");
DynamicMedia dm = getMedia(DynamicMedia.class);
dm.methodForDynamicMedia("somedata", fixedData);
}Calling methods defined in DynamicMedia might need
many data that can only be retrieved through FixedMedia
(or any similar class just as FixedMedia - derived from Media and handle "fixed" data).
So we decide to define a field to contain a reference of FixedMedia or its container (a list, map)
in DynamicMedia to reduce the codes.
But it results the coupling between DynamicMedia and FixedMedia(s).
Which design is better on testing, quality?Why not just use an interface?
And why does methodForDynamicMedia() exist only there?
So we decide to define a field to contain a reference of FixedMedia or its container (a list, map)
in DynamicMedia to reduce the codes.Sounds like a muddled design. Sometimes you might make an implementation decision that adversely impacts the design but you better have a better reason than just because it reduces some code. Maybe it reduces a lot of code, but if so then that might suggest something is wrong with the design. -
i have 3 ipods one for each child.. i need to set it up so that each have access to my account but individually so that they cannot use each others itunes money
Hi Felicia,
Are you wanting them to have access to your account so they can purchase items using your credit card? Or do you want them "sharing" your account for some other reason?
GB -
How many midlets can communicate to each other?
Hi
How many midlets can communicate to each other? Also can we use one midlet as a library for another midlet?
thnx.I mean to say how they can use each other's resources? Is it possible thet one midlet can use other midlets resource? Also can we add or delete the midlet from our application .jar file within the same midlet?
-
Classes are not visible to each other in a same package
Hi,
I have a question. How to make all classes in a same package visible to each other? For example, I have two classes below, T1.java and T2.java:
Below is T1.java
package thesis;
public class T1 {
public T1(){}
public void func1(){
System.out.println("This is in T1 class");
Below is T2.java
package thesis;
public class T2 {
public T2(){}
public void func2(){
System.out.println("This is in T2");
public static void main(String[] args){
T1 t1 = new T1();
t1.func1();
T2 t2 = new T2();
t2.func2();
I create a directory named thesis and put T1.java and T2.java under this folder. But when I try to compile T2.java, it give me error message, seems that T2.java cannot recognize T1.class.
So, can anyone solve this problem for me. Thanks in advance.
jmlingMake sure your classpath env variable is set correctly!
to compile these classes you should have something like:
C: > javac thesis\T2.java
if your classpath is set up correctly (default is CLASSPATH=.) then the above command should work.
If your still having problems, try:
C: > javac thesis\*.java
or compile T1.java first.
Anthony -
Using ExecutorService class from java.util.concurrent package
Dear java programmers,
I have a question regarding the ExecutorService class from java.util.concurrent package.
I want to parse hundreds of files and for this purpose I'm implementing a thread pool. The way I use the ExecutorService class is summarized below:
ExecutorService executor = Executors.newFixedThreadPool(10);
for (int i = 0; i < 1000; i++){
System.out.println("Parsing file No "+i);
executor.submit(new Dock(i));
executor.shutdown();
try {
executor.awaitTermination(30, TimeUnit.SECONDS);
} catch (InterruptedException ex) {
ex.printStackTrace();
executor.shutdownNow();However, the code snippet above creates all the 1000 threads (Dock objects) at once and loads them to the executor, and thus I'm worrying about memory leak. I haven't tested it on 1000 files yet but just on 50 small ones, and even if the program prints out "Parsing file No "+i 50 times at once, it executes normally the threads in the background.
I guess the write way would be to keep the number of active/idle threads in the executor constant (lets say 20 if the thread pool's size is 10) and submit a new one whenever a thread has been finished or terminated. But for this to happen the program should be notified someway whenever a thread is done. Can anybody help me do that?
thanks in advance,
TomOk I found a feasible solution myself although I'm not sure if this is the optimum.
Here's what I did:
ExecutorService executor = Executors.newFixedThreadPool(10);
Future<String> future0, future1, future2, future3, future4, future5, future6, future7, future8, future9;
Future[] futureArray = {future0 = null, future1 = null, future2 = null, future3 = null, future4 = null, future5 = null,
future6 = null, future7 = null, future8 = null, future9 = null};
for (int i = 0; i < 10; i++){
futureArray[i] = executor.submit(new Dock(i));
}I created the ExecutorService object which encapsulates the thread pool and then created 10 Future objects (java.util.concurrent.Future) and added them into an Array.
For java.util.concurrent.Future and Callable Interface usage refer to:
[http://www.swingwiki.org/best:use_worker_thread_for_long_operations]
[http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part1/Java/Chapter10/concurrencyTools.html]
I used a Future[] Array to make the code neater. So after that I submitted -and in this way filled up- the first 10 threads to the thread pool.
int i = 9;
while (i < 1000){
for (int j = 0; j < 10; j++){
if (futureArray[j].isDone() && i < 999){
try{
i++;
futureArray[j] = executor.submit(new Dock(i));
} catch (ExecutionException ex) {
ex.printStackTrace();
} catch (InterruptedException ex) {
ex.printStackTrace();
try {
Thread.sleep(100); // wait a while
} catch(InterruptedException iex) { /* ignore */ }
executor.shutdown();
try {
executor.awaitTermination(60, TimeUnit.SECONDS);
} catch (InterruptedException ex) {
ex.printStackTrace();
executor.shutdownNow();
}Each of the future[0-9] objects represents a thread in the thread pool. So essentially I'm check which of these 10 threads has been finished (using the java.util.concurrent.Future.isDone() method) and if yes I replenish that empty future[0-9] object with a new one. -
How to use the different class for each screen as well as function.
Hi Experts,
How to use the different class for each screen as well as function.
With BestRegards,
M.Thippa Reddy.Hi ThippaReddy,
see this sample code
Public Class ClsMenInBlack
#Region "Declarations"
'Class objects
'UI and Di objects
Dim objForm As SAPbouiCOM.Form
'Variables
Dim strQuery As String
#End Region
#Region "Methods"
Private Function GeRate() As Double
Return Double
End Function
#End Region
Public Sub SBO_Appln_MenuEvent(ByRef pVal As SAPbouiCOM.MenuEvent, ByRef BubbleEvent As Boolean)
If pVal.BeforeAction = True Then
If pVal.MenuUID = "ENV_Menu_MIB" Then
End If
Else ' Before Action False
End If
End Sub
#End Region
End Class
End Class
Rgds
Micheal
Vasu Anna Regional Feeling a???? Just Kidding
Edited by: micheal willis on Jul 27, 2009 5:49 PM
Edited by: micheal willis on Jul 27, 2009 5:50 PM -
How to convert the class in the one package to same class in the other pack
How to convert the class in the one package to same class in the other package
example:
BeanDTO.java
package cho3.hello.bean;
public class BeanDTO {
private String name;
private int age;
* @return
public int getAge() {
return age;
* @return
public String getName() {
return name;
* @param i
public void setAge(int i) {
age = i;
* @param string
public void setName(String string) {
name = string;
BeanDTO.java in other package
package ch03.hello;
public class BeanDTO {
private String name;
private int age;
* @return
public int getAge() {
return age;
* @return
public String getName() {
return name;
* @param i
public void setAge(int i) {
age = i;
* @param string
public void setName(String string) {
name = string;
My converter lass lokks like
public class BeanUtilTest {
public static void main(String[] args) {
try
ch03.hello.BeanDTO bean=new ch03.hello.BeanDTO();
bean.setAge(10);
bean.setName("mahesh");
cho3.hello.bean.BeanDTO beanDto=new cho3.hello.bean.BeanDTO();
ClassConverter classconv=new ClassConverter();
//classconv.
System.out.println("hi "+beanDto.getClass().toString());
System.out.println("hi helli "+bean.toString()+" "+bean.getAge()+" "+bean.getName()+" "+bean.getClass());
Object b=classconv.convert(beanDto.getClass(),(Object)bean);
System.out.println(b.toString());
beanDto= (cho3.hello.bean.BeanDTO)b;
System.out.println(" "+beanDto.getAge()+" "+beanDto.getName() );
}catch(Exception e)
e.printStackTrace();
But its giving class cast exception. Please help on this..Do you mean "two different layers" as in separate JVMs or "two different layers" as in functional areas running within the same JVM.
In either case, if the first class is actually semantically and functionally the same as the second (and they are always intended to be the same) then import and and use the first class in place of the second. That's beyond any question of how to get the data of the first into the second if and when you need to.
Once you make the breakthrough and use one class instead of two I'd guess that almost solves your problem. But if you want to describe your architecture a little that would help others pin down want you're trying to do. -
2 files in same package and depends each other need import package??
test1.java and test2.java are in the same package mypackage,
and test1.java will call methods in test2.java, does it mean
test1.java needs to import mypackage.test2;
i.e.
//test1.java
package mypackage;
import mypackage.test2;
class test1
}no, once classes are in the same packages they are picked up ie tc1 is in tc_package and tc2 is also in tc_package, tc1 need not import tc_package.tc2 to use tc2 methods.
/Paul -
Can I use the inner class of one containing class by the other class
Can I use the inner class of one containing class by the other class in the same package as the containing class
eg I have a class BST which has inner class Enumerator. Can I use the inner class from the other class in the same pacckage as BST?Inner classes do not share the namespace of the package of the containing class. Also they are never visible to other classes in the same package.Believe what you want, then, if you're going to make up your own rules about how Java works. For people interested in how Java actually works, here is an example that shows why that assertion is false:
package com.yawmark.jdc;
public class Outer {
public class Inner {
}And...
package com.yawmark.demo;
import com.yawmark.jdc.*;
public class Demo {
public static void main(String[] args) {
assert new Outer().new Inner() != null;
}~ -
Is Two Classes that call methods from each other possible?
I have a class lets call it
gui and it has a method called addMessage that appends a string onto a text field
i also have a method called JNIinterface that has a method called
sendAlong Takes a string and sends it along which does alot of stuff
K the gui also has a text field and when a button is pushed it needs to call sendAlong
the JNIinterface randomly recieves messages and when it does it has to call AddMessage so they can be displayed
any way to do this??Is Two Classes that call methods from each other possible?Do you mean like this?
class A
static void doB() { B.fromA(); }
static void fromB() {}
class B
static void doA() { A.fromB(); }
static void fromA() {}
.I doubt there is anyway to do exactly that. You can use an interface however.
Interface IB
void fromA();
class A
IB b;
A(IB instance) {b = instance;}
void doB() { b.fromA(); }
void fromB() {}
class B implements IB
static void doA() { A.fromB(); }
void fromA() {}
.Note that you might want to re-examine your design if you have circular references. There is probably something wrong with it. -
I have multiple family members using one apple id and all of our data is going onto each others phones/how do i stop this?
Each person needs to have their own separate Apple ID along with their own separate computer user account and iTunes Library.
-
I have 2 Macbooks each with an account for me and one for my wife. I use one Macbook logged in with my account and my wife uses the other Macbook only logged in on her account. We both make regular time-machine back-ups each on a separate external disk. Is it possible to update her account on my macbook using her external disk without overwriting my stuff on the same Macbook and vice versa?
Time Machine does not do individual accounts. It records the complete drive. So if you were to use her TM backup on your Mac it would make your Mac just like hers. Both yours and her account on your MAC.
Just copy the missing files over from her Mac to yours. If there are differennt programs on each then they would need to be installed on both.
Maybe you are looking for
-
I was with sky and getting 28mbps fibre, I decided to get bt infinity 2 and was told I would get these speeds Your broadband speed We estimate your download speed will be between 46.9Mb and 63.8Mb. We estimate your upload speed will be between 12Mb a
-
How do I put all of the music I have on my Ipad on to my notebook?
I have put all of my music from my PC onto my ipad and iphone... now that I have my Mac Pro I would like to put all of that music (most of which I did not get from iTunes) onto it. Is there a way to simply connect and download from my ipad to my mac
-
Hi I was trying to make payment authorization for my account four times. Still it's not working. Payment authorization product 1 USD $1.00 Status: Cancelled. Somebody know why? Thank you. Peace.
-
Cannot use system rollback segment for non-system tablespace 'TEMP
Hi everyone! I encountered this error: "Cannot use system rollback segment for non-system tablespace 'TEMP" So this is what I did to check if the undo stuffs are online. SQL> select tablespace_name,status from dba_tablespaces; TABLESPACE_NAME
-
Hai Frnd's There are tables (TADIR,TRDIR) which contains the details about the devclass and the program.from which table the source code of the particular program can be retrieved. Thanks in Advance Suganya