General Java Questions - III

Q: I propose that Java should allow multiple inheritance if...
Everyone knows the potential problem with multiple inheritance is when you run into the
problem of having two instances of a grand parent super class.
For example:
class A extends D {int i; }
class B extends D {int i; }
class C extends A,B {}
Potentially, you could have two copies of D for each instance of C.
However, I propose that Java should allow multiple inheritance if there are no instance
variables associated with the abstracts that the base class is extending.

abstract class A { public setX(); public setY(); public setAll() {setX (); setY(); }
abstract class B { public setC(); public setD(); public setBoth()
{setC(); setD(); }
class C extends A,B {}
You won't have two instances of some grandfather class, since A and B doesn't have instances
I hope the next versions of Java explores this issue.
file:///C|/330_new/330_new/general_java-III.htm (1 of 7) [2003-07-22 22:07:55]
General Java Questions III
Answer: It does. They're called interfaces:
interface A { public void setX(); public void setY(); public void setAll(); }
interface B { public void setC(); public void setD(); public void setBoth(); }
interface C extends A,B {};
public abstract class D implements C {
Q: Can I access a private variable of one Object from another Object?
Answer: Yes, if this object of the same class. You can access private field from static method of
the class through an instance of the same class.
Check one example below:
public class Example {
private int privateVar;
Example(int a) {
privateVar = a;
System.out.println("private privateVar = " + privateVar);
public static void main(String[] args) {
Example ex = new Example(5);
Q: Is there a way to know from class X which class called the method foo()?
If class A and class B are calling a method foo() on class X, is there a way to know from class X
which class called the method foo() (they can be either A or B). I know that this can be done by
capturing the stack trace and examining it, but that solution looks expensive as I have to create
a new Throwable object every time and capture stack trace (And I do this quite frequently).
Is there any other elegant solution to do this, any help and direction
is appreciated.
Answer: Pass a reference to the class to the foo() method.
foo(Object x){
file:///C|/330_new/330_new/general_java-III.htm (2 of 7) [2003-07-22 22:07:55]
General Java Questions III
should do it.
Q: Is it possible to stop an object from being created during construction?
For example if an error occurs inside the constructor (e.g. the parameters pass in were invalid)
and I wanted to stop an object being created would it be possible to return null rather than a
reference to a new object. (I know the term return is technically correct in this case but you
know what I mean).
Basically, is it possible to cancel object creation?
Answer: Yes, have the constructor throw an exception. Formally, an object _will_ be created
(since the constructor is a method invoked after the actual method creation), but nothing useful
will be returned to the program, and the dead object will be later reclaimed by Garbage
But the clean way is as another reply suggests, that you leave calls to the constructor to a static
factory method which can check the parameters and return null when needed.
Note that a constructor - or any method in general - throwing an exception will not "return null",
but will leave the "assign target" as it was.
Tor Iver Wilhelmsen

Q: suppose I put a file a.txt in package and the try access it like following. Will it
public class Hello{
File f = new File("a.txt");
it is not working for me. Is there any workaround?
Answer: If the source and the text file are in the jar file, then you access the file by:
URL fileURL = getClass().getResource("file.txt");
You can then read the file by using a reader (or whatever you choose),
_istream = new BufferedReader( new
InputStreamReader(fileURL.openStream()) );
file:///C|/330_new/330_new/general_java-III.htm (3 of 7) [2003-07-22 22:07:55]
General Java Questions III
j o h n e w e b e r
Or, simpler
getClass().getResourcesAsStream("file.txt"), but you must be sure that
file is in the same directory ( package ) as your class, otherwise you
need play with getClassLoader().getResourceAsStream( <path>"/file.txt" );
Q: Difference between loading and instantiating a class???
Well, the subject says it all. What is the difference between loading and instantiating a class in
a JVM.
Second question: What would happen if at runtime I update a class file? Will the JVM know to use that
Answer: The difference is that when a class is loaded by a ClassLoader it is read in as a stream
of bytes, presumably from a file, but it could just as easily be from over the network, and then
processed or "cooked" into a representation that the VM can use to make instances of Objects
of that classes type. This last part is the instantiation. You can load a class at runtime with:
Class.forName( "MyClass" );
and instantiate one with:
MyClass mc = Class.forName( "MyClass" ).newInstance();
Cool, ehh. You don't have to know the name of a class at compile time.
>Second question: What would happen if at runtime I update a class file?
>Will the JVM know to use that instead?
Loaded classes are cached because it's quite costly to do the "cooking" I mentioned above. So
it will not be loaded. You may create a separate ClassLoader with new SecureClassLoader but
that will cause all classes _it_ loads to be loaded from this new ClassLoader but that's not what
you want.
I don't know if you can specify that a class should be loaded from disk again using the normal
ClassLoader. You could very easily make your own ClassLoader in which case you would have
explicit control over such things. Look at java.lang.ClassLoader and java.lang.Class.
Michael B. Allen
file:///C|/330_new/330_new/general_java-III.htm (4 of 7) [2003-07-22 22:07:55]
General Java Questions III
Q: Why developers should not write programs that call 'sun' packages?
Answer: Java Software supports into the future only classes in java.* packages, not sun.*
packages. In general, API in sun.* is subject to change at any time without notice.
A Java program that directly calls into sun.* packages is not guaranteed to work on all Javacompatible
platforms. In fact, such a program is not guaranteed to work even in future versions
on the same platform.
For these reasons, there is no documentation available for the sun.* classes. Platformindependence
is one of the great advantages of developing in the Java programming
language. Furthermore, Sun and our licensees of Java technology are committed to
maintaining backward compatibility of the APIs for future versions of the Java platform. (Except
for code that relies on serious bugs that we later fix.) This means that once your program is
written, the class files will work in future releases.
For more details, see the article Why Developers Should Not Write Programs That Call 'sun'

Q: Can garbage collector remove my singleton?
A usually singleton..
public class Single{
private static Single single;
private Single {}
public static Single getInstance(){
single = new Single();
return single;
Well,, seems good ?
But classes are objects do Java 2 v1.3 class garbagecollecting? Meaning my singleton
could dissapear if i dont keep a refrence to it (or the class itself) somewhere ?
If classes is not garbagecollected, that's pretty stupid, I dont want classes taking up memory
when i perhaps never will use it again....
Answer: No. Classes can define objects. That is, only the dynamic part of the class defines
objects. The static part exists only in one place in memory and can not be duplicated. You can
call the getInstance() method from anywhere in your program.
Java requires however that you tell where to find the method, in this case in the Single class.
Therefore, you should use
file:///C|/330_new/330_new/general_java-III.htm (5 of 7) [2003-07-22 22:07:55]
General Java Questions III
to get the instance. This is (though it looks much like it) not an execution of a method on an
object, but just a method call without object. Single is only used to find out which getInstance()
method should be used, and where it is.
You could add a delete() method if you don't need the instance anymore:
public class Single{
private static Single single;
private Single {}
public static Single getInstance(){
single = new Single();
return single;
public static delete(){
single = null;
The garbage collector can now remove the single object after delete() is called if memory is
Rijk-Jan van Haaften
Dept of Computer Science, Utrecht University, The Netherlands
P.S by John:
Doing more deeper investigation of this question I found one very good article about this topic.
Everybody who are interested can read full article here:
For the rest of our audience shortly:
A Singleton class can be garbage collected and when
".. a Singleton class is garbage-collected and then reloaded, a new Singleton instance is
created. Any class can be garbage-collected when no other object holds reference to the class
or its instances. If no object holds a reference to the ' Singleton object, then the Singleton class
may disappear, later to be reloaded when the Singleton is again needed. In that case, a new
Singleton object will be created. Any static or instance
fields saved for the object will be lost and reinitialized.
This problems exists in older JavaTM Virtual Machines1. JDK 1.2 VMs, in particular, conform to
a newer class garbage collection model that forbids any class in a given classloader to be
collected until all are unreferenced"
And you "... can also set your VM to have no class garbage collection (-Xnoclassgc on the JRE
1.3, or -noclassgc on the IBM JVM). Keep in mind that if you have a long-running program that
frequently reloads classes (perhaps through special class
loaders such as the remote class loaders), you have to consider whether that could cause a
file:///C|/330_new/330_new/general_java-III.htm (6 of 7) [2003-07-22 22:07:55]
General Java Questions III
problematic buildup of garbage classes in the VM."
Also some people asked what is a Singleton and what is relation has it to Java.
Shortly a Singleton is one of classical design patterns that are used in software development.
More please read in free book here:
Q: I study patterns now and would be lost and forget everything very soon! Help!
I am very new to design patterns and just bought the GoF book to learn about it.
But as I complete the first couple of chapters right away, I see that they have 23 different
patterns and I would be lost and forget everything very soon if I sequentially (page by page)
read the entire book!.
Do any of you have recommendations on how to proceed with this book so that I 'll remember
at least some of them by the time I am done with the book? I can see that many of the classes
in java API use composition, facade etc...
But other than that I don't think I 'll be able to gather anything unless I am able to remember
where & when to use particular pattern A, B or C...
Answer: Glad to hear you got the GoF book, it's a great reference manual for patterns. As
you've found, however, it's a bit heavy to just "read." What I recommend to people is that they
pick a few of the easier, more commonly used patterns: Singleton is a no-brainer that pops up
a lot. Adapter tends to get used here and there and isn't that difficult to understand. If you're
doing Swing, then definitely go learn the Observer pattern. It'll help to keep you from mixing
data and interface code. Once you've learned three or four and have used them a few times,
then as you start new projects, look back to the text to see if there are opportunities in your
project where other patterns can be used.
You'll find that over time you'll use more and more of the patterns (some a lot more than others,
obviously). I've often found cases where I missed a pattern during design and had "the light go
on" after I'd written a bunch of code and realized I was either using a known pattern by
accident, or could have used a pattern to my advantage. When possible, I then go back and
adjust the design/code to match the pattern.
Keep in mind that the patterns generally don't appear as "absolute." It's expected that you may
have variations to satisfy your application's needs.
It's really helpful to others, however, if you make a quick note in your design doc/code about
what pattern you were using (which helps them learn patterns too, and helps them understand
what you were up to if they know the pattern already).