Newbie question: custom classes
So I decided to learn Java. I have been going strong for the past 3 days, building a web crawler (I learn by doing).
So far, I love it. I am a good halfway through writing it and i have not gotten stumped till now. I was happily coding away at my main class, when I realized I needed to make a new class.
When I put a public class in the same file with the main class, the compiler complains about it being public.
When it is a private class, I can't use it in my main class.
When I make it a public class and put it in a separate file, the compiler can't find it.
I have searched and searched but what little I can find is ambiguous, making references to strange, unfamiliar constructs.
I miss #import "class.h".
The main class is real long but heres it basically:
public class Crawler {
public static StringBin crawled = new StringBin(3);
public static String domain = "";
public static void main(String[] args) {
crawl("http://www.google.com/");
crawl("http://www.google.com/ig");
public static int crawl(String location) {
Socket socket = null;
try {
String currentURL = location;
//Check/Set uniqueness
if (crawled.contains(currentURL)) {
return 0;
} else {
crawled.add(currentURL);
return 1;
} catch (Exception e) {
System.err.println(e);
return 0;
} finally {
if (socket != null) {
try { socket.close(); }
catch (Exception e) { System.err.println(e); }
}And here is the StringBin class:
public class StringBin {
private static String[] array;
private static int size=0;
private static int increment;
public static void StringBin(int n) {
increment = n;
array = new String[n];
public static void add(String str) {
if (size == array.length) {
String[] newarray = new String[array.length+increment];
System.arraycopy(array, 0, newarray, 0, array.length);
array = newarray;
size++;
array[size] = str;
Arrays.sort(array);
public static Boolean contains(String str) {
int i=Arrays.binarySearch(array, str);
if (i < 0) return false;
return true;
}The purpose of stringbin was to get a relatively efficient way of storing a group of strings and searching within them. I don't even know if it works.
They are in the same folder.
Message was edited by:
111cix
Similar Messages
-
Blatant newbie question: inner classes
I'm trying to pick up java (finally) and am working my way through the tutorial.
I am unclear as to how exactly the Class2.java program works, in the Classes and Inheritance lesson (questions page).
Specifically, when I did the exercise, I 'oopsed' and declared a variable "protected InnerClass2 ic". When I did this, my output showed that "InnerClass1: getAnotherString invoked". When I removed it, it shows "InnerClass2 version of getAnotherString invoked".
Okay... I understand that I screwed up. I'm just having some problems understanding how the scoping works resulting in my error.
If somebody could clear this up for me, I'd appreciate it.
Thanks.
John.
(The address of the page is http://java.sun.com/docs/books/tutorial/java/javaOO/QandE/nested-questions.html )Sorry, here is the explanation:
The declaration of the variable ic in the Class2 hides the variable ic in the parent class. When you do not declare this variable in the child class the class of the ic variable in the parent class will be InnerClass2 (because of the line in the Class2 constructor ic= new InnerClass2()), and the type of this variable is InnerClass1.
Now when you invoke c2.displayStrings() in the main method of the Class2 the parent's displayStrings() method gets invoked (because there is no overriding version of this method in the child class). And in this method two other methods are invoked on the ic variable (which now has the class InnerClass2):
1 - getString() - which has no overriding version in the InnerClass2 class
and
2- getAnotherString() which is overriden in the InnerClass2 class.
So when you invoke those methods getAnotherString() in the child class will be invoked and you get the result: "InnerClass2 version of getAnother String invoked". If you try to override the other method too (getString()) you will get the result in the overriding version of the method.
This happens because the class of the variable ic (belonging to Class1) is InnerClass2 and this class has a method which overrides, and therefore hides, the method in the parent class, so the variable ic can only see the overriding version of the original method. -
Hi, everyone. I've created a class 'Parser' that compiles. Now I want to create and instance of this class and set/get the data members from another class. However, when I try to use it, as seen below, I get an 'javac' error. What am I doing wrong?
public class Tester {
static Parser my_parser = new Parser() ;
public static void main(String[] args)
throws Exception {
.... other stuff
====== javac error =============
bash-2.02$ javac Tester.java
Tester.java:12: cannot resolve symbol
symbol : class Parser
location: class vocalreader.Tester
static Parser my_parser = new Parser() ;
^
Tester.java:12: cannot resolve symbol
symbol : class Parser
location: class vocalreader.Tester
static Parser my_parser = new Parser() ;
^Here the problem is with the CLASSPATH variable. Make sure it is setted corectly (it must include the current directory ".").
As for the static modifier, in this code static refers to the variable my_parser, of type Parser, which in this way is marked as class variable (and it belongs to class Tester). So this variable can be accessed with the following: Tester.my_parser. Why should he remove the static modifier ? It has nothing to do with the methods in the Parser class. -
Hi,
I am trying to run one of the examples in the JWS tutorial, but everytime I go "ant build" it throws the following error
<stuff_up_front>/jaxrpc/common/targets.xml:30: taskdef class org.apache.catalina.ant.DeployTask cannot be found
As far as I know I have all the necessary path and environmental variable set. Only thing I can think of is that I choose not to install the Tomcat that comes bundled with the JWSDP package since I already had tomcat server running on my machine. But my Catalina_Home has been set from a long time and it works with other applications. So I really not sure what I am suppose to do. Help would be very welcomed. Thansk you.Please dis regard I just now noticed the dates on this thread. (I sure hope you have gotten it working by now.)
I did get these examples running. The fact that I had several versions of Tomcat installed by IDE's I think alot of my env.vars where not pointing to the proper place. I ended up just using all the stuff that came with the jwsdp(server and likes). maybe later once I get a greater understanding I can do better. BUT I AM A BIT SLOW. Thanks all.
If you every reply to me type slow so i can keep up. -
I am trying to start my first flash website by using actionscript
and I have a problem with loading image with outside actionsctipt file.
here is the code:
package {
import flash.display.MovieClip;
import flash.display.Loader;
import flash.net.URLRequest;
public class Index_page extends MovieClip {
private var req:URLRequest=new URLRequest("picture/index_page/image_logo.png");
private var logoLoader:Loader = new Loader();
logoLoader.load(req);
addChild(logoLoader);
when I publish the swf file, it comes out the error message saying,
access to undefined property logoLoader as well as req and logoLoader.
and the method addChild also became undefined.
How could that be since I`ve already declared those variables at the beginning?
But, if I put them in a function like this, it works.
public function Index_page() {
logoLoader.load(req);
addChild(logoLoader);
my point is,
Does it neccessary to make so many lines for only loading an image?
or there is a better way to do this. I am not really famiier with package
and class things...thanks for any help!Code within a class must be within a method, or in the constructor. The example you gave:
public class Index_page extends MovieClip {
private var req:URLRequest=new URLRequest("picture/index_page/image_logo.png");
private var logoLoader:Loader = new Loader();
logoLoader.load(req);
addChild(logoLoader);
as code outside of any method... you can't do that. In your second example you placed it in the constructor - the method that is automatically run when the class is instantiated - the method that has the same name as the class. Only variable declarations can go outside a method definition... -
Newb Question :: Custom Devices
I know NOTHING about Adobe Device Central other than what is
on the Adobe Site.
So I am asking and hoping that the professionals can answer
my question.
If I bought Adobe Device Central CS3, can I create my own
device profile for my own homebrew device? Or is Adobe the only one
building new profiles?Yes, you can add your own device profiles. Device central
only comes with profiles for phones that have Flash Lite
preinstalled. If you want to create a profile for a phone that is
Flash Lite capable—but not Flash Lite preinstalled, you
simply modify an XML file.
Some of the advantages, however, of relying on the Adobe
profiles is that:
They contain data that calabrates the speed of the handset.
They contain hi-resolution images of target handsets.
They are up-to-date with the correct capability list of each
device.
Etc. -
No Custom Class in CVP Session?
Hi,
I feel a little like I've just moved into The Twilight Zone here - is this a newbie question?
In my CVP VXML application, I have 2 custom elements that use a custom class. In the beginning of the call flow, I create an instance of the class, assign it to session, and then later in the call flow I retrieve it from session.
CustomObject myAmazingObject = new CustomObject();
actionData.setSessionData("amazingObject", myAmazingObject);
When the object is retrieved from session, I got a ClassCastException when retrieving it, so I added some slightly more defensive code:
CustomObject existingObject = null; //(CustomObject) actionData.getSessionData("amazingObject");
Object anObject = actionData.getSessionData("amazingObject");
System.out.println( "THE OBJECT IS: " + anObject.getClass().getName() );
if( anObject instanceof CustomObject )
existingObject = (CustomObject) anObject;
What I'm wondering is, why the full classname is printed correctly in the logs but the instanceof test fails!
What I need to find out is what needs to happen in order to be able to store/retrieve user-defined classes in the CVP session. Is there a reason this would not be possible? Strings work fine, more "creative" objects seem to be disallowed...
Does the jar containing the object need to be in a special place maybe?
Thanks,
ChrisApparently what happened here is a side-effect of the "Magical Cache Syndrome". :-)
It appears as though Eclipse or the CVP plugins creates a serialized cache of any jars added to a CVP Studio Project, and there may be a test in the caching mechanism that does not update the cache if only the serialVersionUID changes. Thus the package+class name is the same, but the runtime instance becomes incompatible. Maybe?
Changing the package name of the object, rebuilding, redeploying, fixed the issue.
Then again, it may not be a builder issue. It may also be a Tomcat session issue (it uses serialization when bouncing to retain data), though with no active callers in the test environment I'm not sure why Tomcat would even retain a session, and wouldn't the "updateApp" command clobber it?
Does anyone have any detailed technical information on how this entire mechanism works? I only like magic tricks I can fully explain... :-)
Thanks,
Chris -
Total Newbie Question ... Sorry :-(
I know it's a windows thing, and I am now converted to Mac but I gotta know this because it's doing my head in. It's a complete stupid green gilled newbie question.
When installing new programs on a Mac can you create shortcuts to the programs on the Dock? I did what I THOUGHT it would be, i.e I made an Alias and stuck it in the dock, but on rebooting my Mac later on, in place of the shortcuts where 3 question marks which when clicked on did absolutely nothing???
Help?
A.L.I
Windows XP Pro Desktop, Macbook Pro, 60GB iPod Video Mac OS X (10.4.5) OS XYou aren't installing something from a dmg file are you? The dmg is a disk image – kind of a virtual CD. So when you double click the dmg and then get the little disk/hardrive/custom icon on your desktop that is the same as if you had mounted a CD. You then need to drag the application off of that "CD" into your application folder. Then it is truly installed.
You can then "eject" the icon your your desktop. This is what happens when you shutdown and without remounting the image your dock shortcut can't find the original.
Just a thought. -
Using custom classes that are not beans
Hi folks,
Is it possible to use java classes that are not beans. I mean, on a page, could you say Customer cust = new Customer("Jones", 25);
if you had a Customer class with a constructor that took a name and age (String and int).
If so, how do you go about this- do you need to import the class, or put it in a standard location? I'm using Tomcat, and would guess that this would go in WEB-INF/classes?
I hope it's not a stupid question, all the literature seems to be focused on JavaBeans
Any advice on this would be great!Beans are used as putting Java code into a JSP is generally considered bad practice. The advantage of the bean pattern is that you use things like:
<jsp:setProperty name="laBean" property="someSetter" value="someValue" />so that you aren't embedding Java directly into the JSP. I'm not very religious about this particular topic personally and will throw a line or two in here and there.
Having said that though, you can easily use any Java class in a JSP. You'll have to import it first:
<%@ page import="java.util.*" %>And then you can easily use it like in a real Java program. -
Hi everyone...
I'm working on one final part of a Flash piece that's ended being quite a bear for me. So looking forward to wrapping it up! I'm a big-time newbie. This has been an amazing learning experience but boy it has made my brain hurt!
The final issue I'm having invloves importing a custom class that calls a custom application. It's a class/application that I downloaded and am trying to apply to my project. It is an application that adds transform handles around targeted objects.
I'm importing the class as I think I am supposed to but it doesn't work. There aren't any erros but it simply doesn't work.
Here's how I'm doing it...
My .FLA, FloorPlan.FLA, is located in my root folder along with the class file, ApplicationMain.as.
ApplicationMain.as has an import that imports the application called TransformTool.as. TransformTool.as is located in the root as well.
So in scenen 1 on frame 1 of FloorPlan.FLA I have an import written like so...
import ApplicationMain;
In the file ApplicationMain.as I have an import to grab the file TransformTool.as that is written like so...
package {
import flash.display.MovieClip;
import flash.geom.Rectangle;
import flash.events.MouseEvent;
import TransformTool;
public class ApplicationMain extends MovieClip
private var _transformTool;
public function ApplicationMain ()
_transformTool = new TransformTool();
_transformTool.mode = TransformTool.ROTATE;
_transformTool.iconScale = new HandleHintScale();
_transformTool.iconRotate = new HandleHintRotate();
// _transformTool.boundaries = new Rectangle(50, 50, 475, 260);
addChild(_transformTool);
// register targets //
_transformTool.targets = [content_MC.e1, content_MC.e2, content_MC.e3, content_MC.e4, content_MC.f1, content_MC.f2, content_MC.f3, content_MC.f4, content_MC.f5, content_MC.f6, content_MC.f7, content_MC.f8];
_transformTool.activeTarget = content_MC.f8;
// register radio buttons //
// radio1.addEventListener(MouseEvent.CLICK, changeToolMode);
// radio2.addEventListener(MouseEvent.CLICK, changeToolMode);
private function changeToolMode(evt:MouseEvent):void
_transformTool.mode = evt.currentTarget.label.toLowerCase();
Everything but this class/application is working just fine. It doesn't cause any erros and make other items not function. It simply isn't working. And I had it working at the very beginning of the project so I know its not the class/application files causing the problem; other than possible path issues.
I'm stumped, yet again!
Thanks in advance for your help!HandleHintScale and HandleHintRotate are movie clips in the library of the .fla
-
Detecting when exception was thrown using custom class loader
Hello all,
I would like to implement the solution described here - http://stackoverflow.com/questions/75218/how-can-i-detect-when-an-exceptions-been-thrown-globally-in-java - that uses custom class loader in order to detect when an Exeption thrown somewhere in the JVM hosting my app, please note that exceptions might be thrown from 3rd party jars the app is using. So, thanks to help I got from another post, I've managed to code the custom class loader. My question is how can the class loader wrap the original exception, as the methods in ClassLoader deals with classes, not instances. So where should I set the original exception?
Thanks!
Edited by: user9355666 on Sep 28, 2010 10:48 PMuser9355666 wrote:
I think I'm missing something fundumental, forgive me for being slow...
This is what I did so far. For the exception wrapper I made a simple class extens Exception that recieve Exception in its ctor and store it. I also subclassed ClassLoader and override its loadClass(). I've registered it as the system classloader. My thinking was to check in that point that if the requested class is instance of Exception and if yes, returning my wrapper class wrapping this exception. But, since loadClass() return class, how can I set in the wrapper the original exception?
In addition, let's say 2 different places in the code throws NPE, to my understanding the classloader will load NPE only once, so how throwing the NPE in the second time can be detected?you are missing a key point. you should creating a custom implementation of the NPE class which hooks into your detection code in its constructor. from that point forward, anytime any NPE (which is your custom class) is constructed, you can detect it. -
Dynamic invocation of javac with custom class path.
To all the Java Gurus out there,
Consider the following classes:
XYZ/test/TestUtil.java
package test;
class TestUtil {
void useMe() {
}ABC/test/Test.java
package test;
public class Test {
public static void main(String[] args) {
TestUtil t = new TestUtil();
t.useMe();
}The class Test uses package private access to the TestUtil.useMe() method. Then the Test class is packaged into test.jar and the TestUtil class is packaged into testutil.jar.
Our application uses a custom class loader architecture where the test.jar is loaded by class loader "X" and testutil.jar is loaded by class loader "Y". Also Y is the parent class loader of X. When the main() of Test class is run it results into IllegalAccessException as the package private method is being accessed from different class loaders.
We are currently using a dynamic way to detect the dependency between test.jar and testutil.jar and generating the classpath argument to the "javac" ant task which dyncamically invokes the sun.tools.javac.Main class. So while compiling Test class the following command line is generated:
javac -classpath XYZ/testutil.jar Test.java
It compiles fine assuming that the Test class and the TestUtil class are loaded by the same class loader but at runtime this fails.
Is there a way to make "javac" use our runtime class loader architecture to instead of static classpath, so that the access violation is captured at compile time?
Any help is appreciated.
Ravi
PS: If this is not the right forum please point me to the right place to post this questions.Not that I'm aware of - the Java Language is designed to be platform-independent so absolute file paths which is a specific feature of various file systems would naturally not to be mixed up with the object-oriented hierarchy structure.
Just like a compiler wouldn't check if a file exists in
new File("<FilePath>")I don't think you can get compile-time checks for what you have wanted.
Hope this helps~
Alex Lam S.L. -
How to make set up with first call of method of a custom class?
Hello
I have build a custom class with a few custom methods.
Method1 is called per every record of internal table. I need to set up certain parameters tha are the sme for all the calls (populate the range , to fill the internal table , etc). This should be done only once.
call method ZBW_CUSTOM_FUNCTIONS=>METHOD1
exporting
I = parameter1
importing
O = parameter2.
Loop at ....
<itab>-record1 = parameter2
endloop.
Methods2, 3 , 4 dont need any set up.
Can somebody tell me how to do it within class?
ThanksInstance methods (as opposed to static methods) are called on an object, which is an instance of a class. Broadly, think of the class as a template for the creation of objects. The objects created from the class take the same form as the class, but have their own state -- their own attribute values. In pseudo-ABAP (this won't even close to compile), let's say you have the following class:
CLASS cl_class.
STATICS static_attr TYPE string.
DATA attr1 TYPE string.
DATA attr2 TYPE i.
CLASS-METHOD set_static_attr
IMPORTING static_attr TYPE string.
cl_class=>static_attr = static_attr.
ENDMETHOD.
METHOD constructor
IMPORTING attr1 TYPE string
attr2 TYPE i.
me->attr1 = attr1.
me->attr2 = attr2.
ENDMETHOD.
METHOD get_attr1
RETURNING attr1 TYPE string.
attr1 = me->attr1.
ENDMETHOD.
ENDCLASS.
When you create an instance of the class (with CREATE OBJECT oref), the constructor is implicitly called. You can pass parameters to the constructor using: CREATE OBJECT oref EXPORTING attr1 = 'MyString' attr2 = 4.
You then call methods on the instance you have created. So, oref->get_attr1( ) would return 'MyString'.
The constructor is called when the object is created (so, when you call CREATE OBJECT). At this time, the setup is done, and any subsequent methods you call on the object will be able to use the attributes you set up in the constructor. Every object has its own state. If you had another object, oref2, changing its instance attribute values would not affect the values of oref.
Static methods and attributes are different. A static attribute exists only once for all instances of the class -- they share a single value (within an internal session, I think. I'm not sure of the scope off-hand.) You also call static methods on the class itself, not on instances of it, using a different selector (=> instead of ->). So, if you called cl_class=>set_static_attr( static_attr = 'Static string' ), 'Static string' would be the value of static_attr, which belongs to the class cl_class, and not instances of it. (You can also set up a class constructor, which is called when the class is loaded, but that's another subject.)
To answer your question more succinctly: no, the constructor is not called before each method. It is only called when you create the object. Any subsequent methods called on the object can then access its attributes.
Please have a look at [http://help.sap.com/saphelp_nw70ehp2/helpdata/en/48/ad3779b33a11d194f00000e8353423/frameset.htm] for a more thorough treatment of basic object concepts. (The rest of that documentation is very thin, but it'll get you started. Also, it doesn't appear to deal with statics. You'll have to look elsewhere for that.) -
Referencing between custom classes
Hi,
I need some help with the theory of referencing between custom class files.
I have not worked much with custom classes before, but want to learn more.
Is it possible to call for a function in one custom class file from another custom class file?
The files are in the same package (folder).
The first custom class is the one stat starts all the main activities on the movie clip when it is added to the stage.
One of the activities it should start, is starting to add some movie clips to the stage.
I would like to initiate that activity in the first custom class file, but have the detailed code (where, what and when to add) in another custom class file.
Is that possible? When yes, how should it be referenced?
Many thanks in advance!Hi,
Thank you all for your replays.
Got some new terminology – Singelton, Setters and Getters.
Have not come across before:)
I do know the inheritance and have used it. And my little experience with it told me as well – it’s something you shouldn’t go crazy or fanatic with. Overusing it makes things complicated.
Amy, what you descibed is how I normally do use the classes – attach them to the Library symbols.
In my question I meant one concrete Movie Clip which is one sub-part of the application.
The Movie Clip is just an animated picture. That Movie Clip (girlSwim) is attached to the base class GirlSwim.
And that class is at the moment handling the animation for that girl swimming. It would be good to have that code on a sub-level symbol, like the Girl, but as a mask is swimming along as well, it got too complicated for me to code, cross reference the nested symbols. So the code ended up on top level symbol.
In that Movie Clip are other animating symbols as well and they are all handled with other custom classes.
When the girlSwim Movie Clip is activated, it’s on screen, dragonflies start to fly in and fishes start to swim in as well. They are not on the original picture, so not on stage.
And adding them is managed with timers and it continues as long as the Movie Clip is on screen.
At the moment I have all the stuff related to dragonflies and fishes on the first keyframe.
And it all functions nicely.
But as I’m practicing now using class files and keeping my timeline action script free (except some stop and goto staff to handle the timeline animations), I want to get that part of the code into class file as well.
I could but it all into the class GirlSwim and it would function.
But as the animation code for the girl is long enough, I though it would be good to have the code for dragonflies and fishes separate.
But it needs to be initiated by the GirlSwim class.
So … in my little-simple world I thought the following could work .. but it didn’t:)
1180: Call to a possibly undefined method timerStartDragonflies.
package
public class GirlSwim extends MovieClip
public function GirlSwim()
timerStartDragonflies ();
package
public class Dragonflies extends MovieClip
public function Dragonflies ()
//empty
internal function timerStartDragonflies():void
//code for starting timer
etc.
Is something like that possible or should I put it all into the GirlSwim class? -
I'm a relative flash/actionscript newbie. I created a towers
of hanoi solution moving movie clips around using Tweens. This all
worked great when the action script containing the Tween creation
existed on what I guess is the root movie clip (within the Action
script window of my .fla file).
I tried moving the hanoi solution into a custom class
(extending EventDispatcher) and now the tween does not 'run'. I've
stepped through my code with the debugger and added plenty of trace
statements and am pretty sure all the arguments to the Tween
constructor are correct.
_currentTween = new Tween(_movingDiskMc, "_y",
Regular.easeOut, _movingDiskMc._y, _yMin, _duration);
Is there something fundamental I'm missing? Is the frame rate
an issue with the custom class? The value of _duration above is 5.
thx
- Kurtahhhh.... after further review found that my
'onMotionFinished' event handlers were being called but in the
debugger the scope is the Tween class not my Hanoi class. That's
messed up
found the discussion in the help topic regarding scope of
event handlers and using the 'suggested strategy' things are
working fine now
Maybe you are looking for
-
Mapping corresponding field in the internal table
Hi guys I need help with putting XML value into the appropriate fields in the internal table struc. I attempted to use if else condition to map the element name (cname)over to the fields but those internal table within an internal table post an issue
-
My name is showing up as "my info" on someone else's phone
someone else's name is showing as the owner of my phone?
-
HI, How to create sessions in swing. Is there any technique to create session in swing, Help me, Thanks in advance
-
Hi, Just noticed in my iPhoto 6.0.2 that if I straighten before removing red eyes that the position for red eyeing is not "transformed" so it misses the clicked eye... Regards Edward
-
Toad 9.6 为什么无法连接Oracle10
如题,toad9.6能连接Oracle11g,但是无法连接Oracle10g,是版本问题吗??