Help with abstract classes

Hi All,
1. I would like to know if an abstract class can contain a main method?
2.I have a class called KeyTest which is a junit test class and it contains 2 methods called testSymKey() and testAsymKey() which bascially tests for symmetric key generation and assymmetric key generation. My manager has asked me to create an abstract test class for this class and define the methods in the abstract class and then make a subclass of this abstact class. I am not sure how this can be done!! Any help is appreciated.Here is what i have till now
public class KeyTest extends TestCase implements CSFConstants
public static void main(String[] args) throws Exception
junit.textui.TestRunner.run(suite());
protected void setUp() {
public static Test suite()
return(new TestSuite(KeyTest.class));
public void testSymKey() throws CSFException
CSFISymKey loSymKey = CSFManager.getInstance().getSymKey();
loSymKey.init();
loSymKey.generate();
assertTrue(loSymKey.save() != null);
public void testASymKey() throws CSFException
CSFIAsymKey loAsymKey = CSFManager.getInstance().getAsymKey();
loAsymKey.init();
loAsymKey.generate();
assertTrue(loAsymKey.getPublicKey().toString() != null);
assertTrue(loAsymKey.getPrivateKey().toString() != null);

If a class has one or more abstract methods (including if it claims to implement an interface but doesn't provide an implementation for one or more of the interface's methods, which are all implicitly abstract), then the class must be declared abstract.
However, the converse is not true. An abstract class can have all abstract methods, a mix of abstract and concrete methods, all concrete methods, or no methods at all. You can take any class you want and declare it abstract. (Of course, if you do, any code that does new ThatClass(); will now not compile.)

Similar Messages

  • Problems with abstract classes

    I'm reading Java Wireless Blueprints and i'm confused with the functionality of abstract classes, especially in the next section:
    public byte[] getPoster() throws ApplicationException {
    if (poster == null) {
    try {
    poster =
    ModelObjectLoader.getInstance().getMoviePoster(primaryKey);
    } catch (ModelException me) {
    throw new ApplicationException();
    return poster;
    This class invoque to the ModelObjectLoader class that is abstract and after invoque getInstance().getMoviePoster(primaryKey); method. The source code of the class is:
    public abstract class ModelObjectLoader {
    private static ModelObjectLoader instance = null;
    protected ModelObjectLoader() {
    instance = this;
    return;
    public static ModelObjectLoader getInstance() {
    return instance;
    public abstract TheaterSchedule getTheaterSchedule(Theater theater)
    throws ModelException, ApplicationException;
    public abstract Movie getMovie(String movieKey)
    throws ModelException, ApplicationException;
    public abstract Movie getMovie(Movie movie)
    throws ModelException, ApplicationException;
    public abstract byte[] getMoviePoster(String movieKey)
    throws ModelException, ApplicationException;
    public abstract int[][] getMovieShowTimes(String theaterKey, String movieKey)
    throws ModelException, ApplicationException;
    public abstract SeatingPlan getSeatingPlan(String theaterKey,
    String movieKey,
    int[] showTime) throws ModelException,
    ApplicationException;
    I don�t find where is the implementation of the getMoviePoster(primaryKey) method.
    Can you help me to understand.
    Thanks

    public abstract byte[] getMoviePoster(String movieKey)It's an abstract method, which means that any concrete class that extends ModelObjectLoader must implement the method. If you really need to know (you might not), then call getInstance() and output the result of getClass().getName() on that object. That will tell you its type, and then you can go look at the source.

  • Dealing with abstract classes and interfaces with XMLBeans

    I'm quite new to XMLBeans and would like some help. I've got things working when
    you are only saving concreate classes as XML, but when it comes to clesses containing
    interfaces I am running into problems.
    I basically have a collection of XY objects (see below) that I want to save as
    XML.
    I want to convert the following java classes to an xml schema:
    public class XY{
    X x;
    Y y;
    public interface X{
    void setA(int a);
    int getA();
    public interface Y{
    void setB(int b);
    int getB();
    public class X1 implements X{
    void setA(int a);
    int getA();
    //other data to save
    public class X2 implements X{
    void setA(int a);
    int getA();
    //other data to save
    public class Y1 implements Y{
    void setB(int b);
    int getB();
    //other data to save
    public class Y2 implements Y{
    void setB(int b);
    int getB();
    //other data to save
    What would be the best way to convert these to XML Schema? I've looked through
    all the XMLBeans documentation, but it doesn't say anything about dealing with
    interfaces/abstract classes. Is there anywhere else to look?
    Thanks in advance,
    Andrew

    Anurag,
    What I really wanted was a work-around to using substiutionGroups as substitution
    groups are not supported in this release.
    I want to convert the following schema:
    <xsd:complexType name="PublicationType">
    <xsd:sequence>
    <xsd:element name="Title" type="xsd:string"/>
    <xsd:element name="Author" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/>
    <xsd:element name="Date" type="xsd:gYear"/>
    </xsd:sequence>
    </xsd:complexType>
    <xsd:complexType name="BookType">
    <xsd:complexContent>
    <xsd:extension base="PublicationType" >
    <xsd:sequence>
    <xsd:element name="ISBN" type="xsd:string"/>
    <xsd:element name="Publisher" type="xsd:string"/>
    </xsd:sequence>
    </xsd:extension>
    </xsd:complexContent>
    </xsd:complexType>
    <xsd:complexType name="MagazineType">
    <xsd:complexContent>
    <xsd:restriction base="PublicationType">
    <xsd:sequence>
    <xsd:element name="Title" type="xsd:string"/>
    <xsd:element name="Date" type="xsd:gYear"/>
    </xsd:sequence>
    </xsd:restriction>
    </xsd:complexContent>
    </xsd:complexType>
    <xsd:element name="Publication" type="PublicationType"/>
    <xsd:element name="Book" substitutionGroup="Publication" type="BookType"/>
    <xsd:element name="Magazine" substitutionGroup="Publication" type="MagazineType"/>
    <xsd:element name="BookStore">
    <xsd:complexType>
    <xsd:sequence>
    <xsd:element ref="Publication" maxOccurs="unbounded"/>
    </xsd:sequence>
    </xsd:complexType>
    </xsd:element>
    to produce an XML file like:
    <?xml version="1.0"?>
    <BookStore ¡Ä>
    <Book>
    <Title>Illusions: The Adventures of a Reluctant Messiah</Title>
    <Author>Richard Bach</Author>
    <Date>1977</Date>
    <ISBN>0-440-34319-4</ISBN>
    <Publisher>Dell Publishing Co.</Publisher>
    </Book>
    <Magazine>
    <Title>Natural Health</Title>
    <Date>1999</Date>
    </Magazine>
    <Book>
    <Title>The First and Last Freedom</Title>
    <Author>J. Krishnamurti</Author>
    <Date>1954</Date>
    <ISBN>0-06-064831-7</ISBN>
    <Publisher>Harper & Row</Publisher>
    </Book>
    </BookStore>
    What is the best way to do this without using substitution types?
    Thanks,
    Andrew
    "Anurag" <[email protected]> wrote:
    Andrew,
    Could you please paste/attach a sample of the code you are using to convert
    Java bean classes to XMLBeans?
    In the current release the goal of XMLBeans technology was to convert
    from
    XML Schemas or XML files to XMLBeans. The focus was not towards conversion
    of Java beans to XMLBeans.
    Regards,
    Anurag
    "Andrew" <[email protected]> wrote in message news:[email protected]...
    I'm quite new to XMLBeans and would like some help. I've got thingsworking when
    you are only saving concreate classes as XML, but when it comes toclesses
    containing
    interfaces I am running into problems.
    I basically have a collection of XY objects (see below) that I wantto
    save as
    XML.
    I want to convert the following java classes to an xml schema:
    public class XY{
    X x;
    Y y;
    public interface X{
    void setA(int a);
    int getA();
    public interface Y{
    void setB(int b);
    int getB();
    public class X1 implements X{
    void setA(int a);
    int getA();
    //other data to save
    public class X2 implements X{
    void setA(int a);
    int getA();
    //other data to save
    public class Y1 implements Y{
    void setB(int b);
    int getB();
    //other data to save
    public class Y2 implements Y{
    void setB(int b);
    int getB();
    //other data to save
    What would be the best way to convert these to XML Schema? I've lookedthrough
    all the XMLBeans documentation, but it doesn't say anything about dealingwith
    interfaces/abstract classes. Is there anywhere else to look?
    Thanks in advance,
    Andrew

  • Help with SMTP class function with authentication

    My server is no longer supporting the php mail() functionality.  I need to use SMTP class function with authentication in my php code and they suggested this to replace it: http://www.yrhostsupport.com/index.php?/Knowledgebase/Article/View/101/2/smtp-class-functi on-with-authentication-in-php-code
    So I tried it, but can't get it to work. This is my test form:
    <form method="post" action="forms/sendmail-test2.php" onsubmit="return checkEmail(this);">
    <script type="text/javascript" language="JavaScript">
    </script>
    <fieldset><legend>Info</legend>
    <label> Name </label>
      <input type="text"
      name="name" size="30" maxlength="40"/><br />
    <label> <span class="redText">*</span> Email </label>
        <input name="email" type="text" size="30" maxlength="40"/>
        <br />
    <label><span class="redText">*</span> Message </label>
      <textarea cols="40" rows="5" name="message" type="text" /></textarea><br />
        </fieldset>
    <input type="reset" value="Reset" />
    <input type=submit value="Submit Form" />
    </fieldset>
    </form>
    This is sendmail-test2.php where the form goes. It won't send unless I comment out the first 10 lines.
    <?php
    include('Mail.php');
    //$to = "[email protected]";
    //$name = $_REQUEST['name'] ;
    //$email = $_REQUEST['email'] ;
    //$message = $_REQUEST['name'] ;
    //$headers = "From: $email";
    //$subject = " price quote";
    //$fields = array();
    //$fields{"name"} = "Name"; 
    //$fields{"email"} = "Email";
    //$fields{"message"} = "Message";
    $recipients = '[email protected]'; //CHANGE
    $headers['From']    = '[email protected]'; //CHANGE
    $headers['To']      = '[email protected]'; //CHANGE
    $headers['Subject'] = 'Test message';
    $body = 'Test message';
    // Define SMTP Parameters
    $params['host'] = 'levy.dnsbox25.com';
    $params['port'] = '25';
    $params['auth'] = 'PLAIN';
    $params['username'] = '[email protected]'; //CHANGE
    $params['password'] = 'xxxxxx'; //CHANGE
    /* The following option enables SMTP debugging and will print the SMTP
    conversation to the page, it will only help with authentication issues. */
    $params['debug'] = 'true';
    // Create the mail object using the Mail::factory method
    $mail_object =& Mail::factory('smtp', $params);
    // Print the parameters you are using to the page
    foreach ($params as $p){
          echo "$p<br />";
    // Send the message
    $mail_object->send($recipients, $headers, $body);
    ?>
    It used to work fine when I used
    $send = mail($to, $subject, $body, $headers);
    $send2 = mail($from, $subject2, $autoreply, $headers2);
    But they said I can't use it any more. I'm good with HTML and CSS but I don't know much about php. Thanks for any help integrating a from into this new code!

    Thanks, bregent. I changed it to this and it sends, but nothing shows up in the body except "Test message". How would I "insert the form fields' 'email' and 'name' and 'message' in the body"?
    <?php
    include('Mail.php');
    $to = "[email protected]";
    $name = $_REQUEST['name'] ;
    $email = $_REQUEST['email'] ;
    $message = $_REQUEST['name'] ;
    //$headers = "From: $email";
    $subject = " price quote";
    $fields = array();
    $fields{"name"} = "Name"; 
    $fields{"email"} = "Email";
    $fields{"message"} = "Message";
    $recipients = '[email protected]'; //CHANGE
    $headers['From']    = '[email protected]'; //CHANGE
    $headers['To']      = '[email protected]'; //CHANGE
    $headers['Subject'] = 'Test message';
    $body = 'Test message';
    $fields = array();
    $fields{"name"} = "Name"; 
    $fields{"email"} = "Email";
    $fields{"message"} = "Message";
    // Define SMTP Parameters
    $params['host'] = 'levy.dnsbox25.com';
    $params['port'] = '25';
    $params['auth'] = 'PLAIN';
    $params['username'] = '[email protected]'; //CHANGE
    $params['password'] = xxx'; //CHANGE
    /* The following option enables SMTP debugging and will print the SMTP
    conversation to the page, it will only help with authentication issues. */
    $params['debug'] = 'true';
    // Create the mail object using the Mail::factory method
    $mail_object =& Mail::factory('smtp', $params);
    // Print the parameters you are using to the page
    foreach ($params as $p){
          echo "$p<br />";
    // Send the message
    $mail_object->send($recipients, $headers, $body);
    ?>

  • Mixing polymorphism with abstract classes???

    Hi,
    Can you have polymorhism with abstract superclasses in Java?
    For example, say I have a superclass called Pet:
    abstract class Pet {
         private String name;
         public String getName() {
              return name;
        public void setName(String petName) {
             name = petName;
        public String speak() {
             return "I am a Pet";
    }Now I have a Cat subclass:
    public class Cat extends Pet{
        public String speak {
             return "i am a cat";
    public class Dog extends Pet {
    public String fetch() {
         return "fetching a stick";
    }In my test method I have:
    public class TestPet {
         public static void main(String[] args) {
              Pet p = new Pet();
              System.out.println(p.speak());
              Pet p = new Dog();
              System.out.println(((Dog)p).fetch());
              Pet p = new Cat();
              System.out.println(p.speak() +" is now a cat");
    }So it appears to me that you cannot have polymorphic methods with an abstract superclass - is this right?
    Cheers.

    cotton.m wrote:
    List<Pet> pets = new ArrayList<Pet>();
    I was working (more or less) along the same lines...
    package forums;
    import java.util.List;
    import java.util.ArrayList;
    abstract class Pet
      private String name;
      public String getName() { return this.name; }
      public void setName(String name) { this.name = name; }
      public String speak() {
        return "I am a Pet";
      public abstract String fetch(); // <<<<< the new bit.
      public String getClassName() {
        final String name = this.getClass().getName();
        return name.substring(name.lastIndexOf('.')+1).toLowerCase();
    class Cat extends Pet
      public Cat(String name) {
        setName(name);
      public String speak() {
        return "I am a cat";
      public String fetch() {
        return "No. I am a cat!";
      public String rollOver() {
        return "No. I am a cat!";
    class Dog extends Pet
      public Dog(String name) {
        setName(name);
      public String fetch() {
        return "Look boss, I'm fetching the stick.";
      public String sit() {
        return "Look boss, I'm sitting!";
    public class PetTest
      public static void main(String[] args) {
        List<Pet> pets = new ArrayList<Pet>();
        pets.add(new Cat("Fungus"));
        pets.add(new Dog("Spike"));
        for ( Pet pet : pets ) {
          System.out.println("\""+pet.speak()+"\" said "+pet.getName()+" the "+pet.getClassName()+".");
          System.out.println("\"Go fetch\" said the master.");
          System.out.println("\""+pet.fetch()+"\" said "+pet.getName()+".");
          System.out.println();
        System.out.println("Therefore we conclude that dogs are much better pets.");
    }Both these examples demonstrate that polymorphism is very useful when we have a list of different-type-if-things which have a common interface... i.e. different classes which have (a) a common ancestor; or (b) a common interface... allowing us to treat those different types-of-things as if they where one-type-of-thing, except the-different-types actually do different stuff internally, which is appropriate-to-there-specific-type.
    That's the essence of polymorphism... and, of course, this seperation of "type" and "implementation" isn't limited to lists-of-stuff... it can be very useful all over the show.
    Cheers. Keith.
    Edited by: corlettk on 10/05/2009 11:01 ~~ That's a bit clearer.

  • Using common methods with abstract classes

    hello everyone, i wanted to know if it is bad practice (i imagine it is) to place methods which will be used by multiple classes (computational methods) in an abstract class and mark them as static. When i do this they are always project wide utility classes which dont need an instantiation. When using any of these methods which are common to a project i can then just use..
    Type result = ClassName.DoStaticMethod(...);Thanks for any input,
    Dori
    Edited by: Sir_Dori on Dec 8, 2008 2:01 AM

    Depends on what the methods are meant to do, but I wouldn't make the class abstract. I would instead declare it to be final and have a private constructor.
    Kaj
    Ps. Take a look at the java.lang.Match class.

  • Please help with simple Classes understanding

    Working further to understand Class formation, and basics.
    At the Java Threads Tutorial site:
    http://java.sun.com/docs/books/tutorial/essential/threads/timer.html
    Goal:
    1)To take the following code, and make it into 2 seperate files.
    Reminder.java
    RemindTask.java
    2)Error Free
    Here is the original, functioning code:
    import java.util.Timer;
    import java.util.TimerTask;
    * Simple demo that uses java.util.Timer to schedule a task
    * to execute once 5 seconds have passed.
    * http://java.sun.com/docs/books/tutorial/essential/threads/timer.html
    public class Reminder {
        Timer timer;
        public Reminder(int seconds) {
            timer = new Timer();
            timer.schedule(new RemindTask(), seconds*1000);
        class RemindTask extends TimerTask {
            public void run() {
                System.out.println("Time's up!");
                timer.cancel(); //Terminate the timer thread
        public static void main(String args[]) {
            new Reminder(5);
            System.out.println("Task scheduled.");
    }Here is what I tried to 2 so far, seperate into 2 seperate files:
    Reminder.java
    package threadspack;    //added this
    import java.util.Timer;
    import java.util.TimerTask;
    * Simple demo that uses java.util.Timer to schedule a task
    * to execute once 5 seconds have passed.
    * http://java.sun.com/docs/books/tutorial/essential/threads/timer.html
    public class Reminder {
        Timer timer;
        public Reminder(int seconds) {
            timer = new Timer();
            timer.schedule(new RemindTask(), seconds*1000);
        public static void main(String args[]) {
            new Reminder(5);
            System.out.println("Task scheduled.");
    }and into
    RemindTask.java
    package threadspack;  //added this
    import java.util.Timer;
    import java.util.TimerTask;
    import threadspack.Reminder; //added this
    * http://java.sun.com/docs/books/tutorial/essential/threads/timer.html
    public class RemindTask extends TimerTask
    Timer timer; /**here, I added this, because got a
    "cannot resolve symbol" error if try to compile w/out it
    but I thought using packages would have negated the need to do this....?*/
         public void run() {
                System.out.println("Time's up!");
                timer.cancel(); //Terminate the timer thread
    }After executing Reminder, the program does perform, even does the timing, however, a NullPointerException error is thrown in the RemindTask class because of this line:
    timer.cancel(); //Terminate the timer thread
    I am not sure of:
    If I have packages/import statements setup correctly
    If I have the "Timer" variable setup incorrectly/wrong spot.
    ...how to fix the problem(s)
    Thank you!

    Hi there!
    I understand that somehow the original "Timer" must
    be referenced.
    This is a major point of confusion for me....I
    thought that when importing
    Classes from the same package/other packages, you
    would have directly
    access to the variables within the imported Classes.I think you have one of the basic points of confussion. You are mixing up the concept of a "Class" with the concept of an "Object".
    Now, first of all, you do not need packages at all for what you are trying to do, so my advice is you completely forget about packages for the moment, they will only mess you up more. Simply place both .class files (compiled .java files) in the same directory. Your program is executing fine, so that indicates that the directory in which you have your main class file is being included in your classpath, so the JVM will find any class file you place there.
    As for Classes/Objects, think of the Class as the map in which the structure of a building is designed, and think of the Object as the building itself. Using the same technical map the architect defines, you could build as many buildings as you wanted. They could each have different colors, different types of doors, different window decorations, etc... but they would all have the same basic structure: the one defined in the technical map. So, the technical map is the Class, and each of the buildings is an object. In Java terminology, you would say that each of the buildings is an "Instance" of the Class.
    Lets take a simpler example with a class representing icecreams. Imagine you code the following class:
    public class Icecream{
         String flavor;
         boolean hasChocoChips;
    }Ok, with this code, what you're doing is defining the "structure" of an icecream. You can see that we have two variables in our class: a String variable with the description of the icecream's flavor, and a boolean variable indicating whether or not the icecream has chocolate chips. However, with that code you are not actually CREATING those variables (that is, allocating memory space for that data). All you are doing is saying that EACH icecream which is created will have those two variables. As I mentioned before, in Java terminology, creating an icecream would be instantiating an Icrecream object from the Icecream class.
    Ok, so lets make icrecream!!!
    Ummm... Why would we want to make several icecreams? Well, lets assume we have an icecream store:
    public class IcecreamStore{
    }Now, we want to sell icecreams, so lets put icecreams in our icecream store:
    public class IcecreamStore{
         Icecream strawberryIcecream = new Icecream(); //This is an object, it's an instance of Class Icecream
         Icecream lemonIcecream = new Icecream(); //This is another object, it's an instance of Class Icecream
    }By creating the two Icecream objects you have actually created (allocated memory space) the String and boolean variable for EACH of those icecreams. So you have actually created two String variables and two boolean variables.
    And how do we reference variables, objects, etc...?
    Well, we're selling icecreams, so lets create an icecream salesman:
    public class IcecreamSalesMan{
    }Our icecream salesman wants to sell icecreams, so lets give him a store. Lets say that each icecream store can only hold 3 icecreams. We could then define the IcecreamStore class as follows:
    public class IcecreamStore{
         Icecream icecream1;
         Icecream icecream2;
         Icecream icecream3;
    }Now lets modify our IcecreamSalesMan class to give the guy an icecream store:
    public class IcecreamSalesMan{
         IcecreamStore store = new IcecreamStore();
    }Ok, so now we have within our IcecreamSalesMan class a variable, called "store" which is itself an object (an instance) of the calss IcecreamStore.
    Now, as defined above, our IcecreamStore class will have three Icecream objects. Indirectly, our icecream salesman has now three icecreams, since he has an IcecreamStore object which in turn holds three Icecream objects.
    On the other hand, our good old salesman wants the three icecreams in his store to be chocolate, strawberry, and orange flavored. And he wants the two first icecreams to have chocolate chips, but not the third one. Well, here's the whole thing in java language:
    public class Icecream{ //define the Icecream class
         String flavor;
         boolean hasChocoChips;
    public class IcecreamStore{ //define the IcecreamStore class
         //Each icecream store will have three icecreams
         Icecream icecream1 = new Icecream(); //Create an Icecream object
         Icecream icecream2 = new Icecream(); //Create another Icecream object
         Icecream icecream3 = new Icecream(); //Create another Icecream object
    public class IcecreamSalesMan{ //this is our main (executable) class
         IcecreamStore store; //Our class has a variable which is an IcecreamStore object
         public void main(String args[]){
              store = new IcecreamStore(); //Create the store object (which itself will have 3 Icecream objects)
              /*Put the flavors and chocolate chips:*/
              store.icecream1.flavor = "Chocolate"; //Variable "flavor" of variable "icecream1" of variable "store"
              store.icecream2.flavor = "Strawberry"; //Variable "flavor" of variable "icecream2" of variable "store"
              store.icecream3.flavor = "Orange";
              store.icecream1.hasChocoChips = true;
              store.icecream2.hasChocoChips = true;
              store.icecream3.hasChocoChips = false;
    }And, retaking your original question, each of these three classes (Icecream, IcecreamStore, and IcecreamSalesMan) could be in a different .java file, and the program would work just fine. No need for packages!
    I'm sorry if you already knew all this and I just gave you a stupid lecture, but from your post I got the impression that you didn't have these concepts very clear. Otherwise, if you got the point, I'll let your extrapolate it to your own code. Should be a pice of cake!

  • Help With Multiple Class Objects With Methods

    I am dealing with multiple classes. I am wondering why I am getting an error on this line it's by the bottom
              obj1.array() = newArray[i];
    It gives the array out of bounds. On another note I believe I can change obj1 to just like incomingArray if I wanted correct since it's just a reference because I should be able to do this method sort on any array.
    method : selSort
    input - none
    output - void
    This is where we sort the arary
    Pseudocode Code:
    1 Initialize variable oldlocation to hold spot of smallest number in original array
    2 Initialize variable smallnumber to store smallest number in original array
    3 Initialize new integer array
    4 Set new array length to length of original array
    5 Initialize variable length to store lengh of new array
    6 For i = 0 and continue till i < new array length
    6.1 Find smallest number in original array
    6.2 Put the smallest number in new array
    6.3 Remove smallest number from original array
    7 Copy contents of new array that is sorted to original array
    Basic concept is to repetitively find the smallest
    (or largest) item in the original array. Once smallest
    is found, move it to the next spot in a new array and
    remove it from the old array.
    public void selSort ()
         int oldlocation = 0;
         int smallnumber = 0;
         int [] newArray = obj1.array();
         newArray = new int [obj1.length()];
         int length = newArray.length;
         for (int i = 0; i < newArray.length; i++)
    //          System.out.println("Test 1");
              newArray[i] = obj1.sortSmall();
    //          System.out.println("Test 2");
              smallnumber = obj1.sortSmall();
    //          System.out.println("This is the smallest number " + smallnumber);
              oldlocation = obj1.location(smallnumber);
    //          System.out.println("This is the old location " + oldlocation);
    //          System.out.println("Test 3");
              obj1.removeLocation(oldlocation);
    //          System.out.println("Test 4");
         System.out.println();
         System.out.println("The sorted array looks like");
         for (int k = 0; k < newArray.length; k++)
              System.out.print(newArray[k] + " ");
         System.out.println();
         System.out.println();
         obj1.resize(newArray.length);
         for (int i = 0; i < newArray.length; i++)
              obj1.array()[i] = newArray[i];
         return;

    method : selSort
    input - none
    output - void
    This is where we sort the arary
    Pseudocode Code:
    1 Initialize variable oldlocation to hold spot of smallest number in original array
    2 Initialize variable smallnumber to store smallest number in original array
    3 Initialize new integer array
    4 Set new array length to length of original array
    5 Initialize variable length to store lengh of new array
    6 For i = 0 and continue till i < new array length
    6.1 Find smallest number in original array
    6.2 Put the smallest number in new array
    6.3 Remove smallest number from original array
    7 Copy contents of new array that is sorted to original array
    Basic concept is to repetitively find the smallest
    (or largest) item in the original array. Once smallest
    is found, move it to the next spot in a new array and
    remove it from the old array.
    public void selSort ()
         int oldlocation = 0;
         int smallnumber = 0;
         int [] newArray = obj1.array();
         newArray = new int [obj1.length()];
         int length = newArray.length;
         for (int i = 0; i < newArray.length; i++)
    //          System.out.println("Test 1");
              newArray[i] = obj1.sortSmall();
    //          System.out.println("Test 2");
              smallnumber = obj1.sortSmall();
    //          System.out.println("This is the smallest number " + smallnumber);
              oldlocation = obj1.location(smallnumber);
    //          System.out.println("This is the old location " + oldlocation);
    //          System.out.println("Test 3");
              obj1.removeLocation(oldlocation);
    //          System.out.println("Test 4");
         System.out.println();
         System.out.println("The sorted array looks like");
         for (int k = 0; k < newArray.length; k++)
              System.out.print(newArray[k] + " ");
         System.out.println();
         System.out.println();
         obj1.resize(newArray.length);
         for (int i = 0; i < newArray.length; i++)
              obj1.array() = newArray[i];
         return;

  • Help with Runtime class and timeout of Process

    Hi,
    Question regarding using Runtime class, and yes I have looked at the javadocs, but I am still confused and frustrated.
    Here is part of my code.
    Process p;
    Runtime runtime = Runtime.getRuntime();
    p = runtime.exec("rsh localhost ls");
    if you are not familiar with rsh all it does is remote shell into the computer localhost and executes the command ls.
    Now, I dont have rsh running on my computer so it will hang at that line for about 40 sec and eventually time out on its own. Is there anyway I can specify a timeout argument like there is for the ping command? Like if there is no response from localhost after 3 sec, then just kill the process?
    I looked at the Runtime javadoc and Process javadoc and the closest thing I could come to with is something to do with envp (environment parameters), but I dont know what that is.
    Thanks guys.

    You can't timeout the "runtime.exec("rsh localhost ls");" call but if you execute the call in a seperate thread you can "timeout" and continue executing on the original thread (while letting the "runtime" thread to timeout on its own).
    Check the following class that I created for cases like this:
    abstract public class TimeoutHelper implements Runnable
        private Throwable error;
        private boolean running = true;
        private Object retValue;
        protected String name;
        private long waitTime;
        private Thread thread;
         * Creates a new helper. Use {@link #start} to run the code.
         * @param name A name that will be used in the helper thread name
         * @param waitTime The time (in msec) to wait before timeout.
        public TimeoutHelper(String name, long waitTime)
            this.name = name;
            this.waitTime = waitTime;
        public Object start() throws Throwable
            return asyncExecute();
        abstract protected Object execute() throws Throwable;
        private synchronized Object asyncExecute() throws Throwable
            createThread().start();
            if (running)
                try
                    wait(waitTime);
                    if (running)
                        // Timeout!!
                        abortThread();
                        throw new TimeOutException("Timeout for: " + name);
                catch (InterruptedException ie)
                    // Ignore
            if (error != null)
                throw error;
            return retValue;
        private void abortThread()
            if (thread != null)
                thread.interrupt();
        protected Thread createThread()
            thread = new Thread(this, name);
            return thread;
        public void run()
            try
                retValue = execute();
            catch (Throwable th)
                error = th;
            synchronized (this)
                running = false;
                notifyAll();
    }You use the class by extending it and implementing "execute". For example:
            TimeoutHelper helper = new TimeoutHelper("Runner", 5000)
                protected Object execute() throws Throwable
                    Runtime runtime = Runtime.getRuntime();
                    return runtime.exec("rsh localhost ls");
            try
                Process p = (Process)helper.start();
            catch (TimeOutException e)
                // Handle timeout here
            catch (Exception e)
                // Handle other errors here.
            }

  • Help with objects, classes, etc...

    Im having a little trouble grasping the concept of all of these names. I know that every Java program is a class. Now, is a method what we call in C++ a function? It seems as though this is what it is while reading this book but just want to clarify it. And also, what is a good defninition for an object. I know that parseInt() is an object but does that mean that is is some kind of function/method that was declared or made in a class?

    lol ... ok; it's easy to get caught up in the jargon...
    A class is a "type" of thing, complete with values which describe the thing and operations that the thing can perform. For instance, a "dog" can be described in terms of its breed, size, markings, and things that it does (eat, do tricks, bark, etc).
    An object is a dinstinct instance of a class. So, if you are talking about one particular dog, let's say Lassie, you can describe it as a collie, of a certain size, etc, etc.
    Object oriented programming makes use of this jargon. The act of creating an object from a class description is known as "instantiation".
    You mentioned C++. In C++, you can have functions which stand alone, or functions which are part of classes. C++ functions which are part of class definitions are known as "member functions"; Java methods are like C++ member functions.
    now, on to parseInt(). remember how we said that a class definition can define operations (like "eat", for a dog)? well, although we can define the eat operation, only a instance of dog (e.g., Lassie) can actually perform the operation. so, if you have Lassie and RinTinTin in front of you, and you say, "Lassie, bark!", only Lassie will perform that operation.
    in object oriented programming, a method which makes sense for one object (that is, one particular instance of a class) to perform is known as an instance method. there's another abstraction, though... you can define variables and methods which belong to all instances of a class (as a group), rather than any one particular object. These are known as class variables and class methods, and Java uses the keyword "static" to identify them.
    So, if I had the class dog, it might look a little like:
    public class Dog {
        private float weight;  // each dog object will have its own weight variable
        static private int count;  // this is shared by all instantiated dog objects!
        public void bark() {
            // instance method.  call this with respect to a particular dog object
            System.out.println ("Woof.");
        public static int getCount() {
            // this method is shared by all instantiated dog objects.  It's called using the syntax
            // Dog.getCount(), rather than by instantiating a dog object and using the object to call
            // the method
            return count;
    // etc...
    }Does that make sense? some variables belong to each particular instantiated object, while others don't need an object in order to refer to them.
    one more thing: in Java, there are objects and there are primitives. the primitives are data types such as int, float, boolean, etc. Java also provides wrappers for these primitives, so you can refer to them in object contexts; for example, Integer, Boolean, etc.
    OK... now back to your question. parseInt() is a static method of class Integer. (therefore, you don't need an instance of Integer in order to call parseInt().
    the parseInt() method returns an int.
    make sense?

  • Need Help with new Classes / methods

    Hi, I need to create a class called Proposition. It include a Proposition object with 3 variables
    Name, Description, Value
    This is the constructor I wrote:
    private String name;
    private String description;
    private boolean value;
    public Proposition(){
              name = "name";
              description = "description";
              value = false;
    }Now I need a method that give values to the 3 variables in the proposition object:
         public Proposition setProp(String line){
              StringTokenizer ST1 = new StringTokenizer(line, ".");
              String ValidLine = ST1.nextToken()+".";
              StringTokenizer ST2 = new StringTokenizer(ValidLine, "=");
              name = CutSpace(ST2.nextToken());
              description = (ST2.nextToken()).trim();
              value = false;
              return name;
              return description;
              return value;
         }An example of String line is: v = we are in Vancouver.
    When I run the program, I got error message with the 3 return statements saying found String/Boolean while Proposition is needed. I'm not quite sure how to write the return statements. Can any1 help?
    Thx!

    Your setProp() method should not be returning anything. After all it is setting not getting. So just declare it as
    public void setProp(String line){and remove the return statements.

  • Need help with a Class.

    Ok hey guys i got A project for school and i need help. I asked my teacher and he num so yea. here it is
    this is my blog class
    /* Project Name: .java
                 Name:
                Class: Programing 2 #0047-02 Pds 5&6
      Variable List:
                   Info:
    import java.util.Scanner;
    import java.util.Date;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    public class blog
         String date2;
         String user;
         String Entry;
         public void GetInfo(String Iuser,String IEntry)
              DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
              Date date = new Date();
              date2 = dateFormat.format(date);
              user = Iuser;
              Entry = IEntry:
         public void ShowInfo()
              System.out.println(date2 + " " + user + " Said: " + Entry);
    }This is my test class
    /* Project Name: .java
                 Name: Josh
                Class: Programing 2 #0047-02 Pds 5&6
      Variable List:
                   Info:
    import java.util.Scanner;
    public class test
         String user;
         String Entry;
         public static void main (String[] args)
         {     System.out.println("Welcome Please Eneter UserName");
              Scanner kb = new Scanner(System.in);
              user = kb.next();
              System.out.println("Please Enter Your Entry");
              Entry = kb.next();
              blog info = new blog();
              blog.GetInfo(user,Entry);
              blog.ShowInfo();
    }So what is sopost to do in the test it ask user to import user name and entery. It send it to blog Class, then it send it out. Here is my errors
    G:\VOC T2\Java\Chap4\test.java:21: non-static variable user cannot be referenced from a static context
              user = kb.next();
              ^
    G:\VOC T2\Java\Chap4\test.java:25: non-static variable Entry cannot be referenced from a static context
              Entry = kb.next();
              ^
    G:\VOC T2\Java\Chap4\test.java:29: non-static variable user cannot be referenced from a static context
              blog.GetInfo(user,Entry);
                           ^
    G:\VOC T2\Java\Chap4\test.java:29: non-static variable Entry cannot be referenced from a static context
              blog.GetInfo(user,Entry);
                                ^
    G:\VOC T2\Java\Chap4\test.java:29: GetInfo(java.lang.String,java.lang.String,java.lang.String) in blog cannot be applied to (java.lang.String,java.lang.String)
              blog.GetInfo(user,Entry);
                  ^
    G:\VOC T2\Java\Chap4\test.java:31: non-static method ShowInfo() cannot be referenced from a static context
              blog.ShowInfo();
                  ^
    6 errors
    Tool completed with exit code 1 Plez help

    -- "non-static X cannot be referenced from a static context" --
    You get this error because static members don't require an instance of the object to be accessed; they belong to the class. But a non-static member belongs to an instance (an individual object). There's no way for the static method to know which instance's variable to use or method to call, and thus, the compiler happily tells you that you can't access an instance member (non-static) from a class context (static).
    [The Java? Tutorial - Understanding Instance and Class Members|http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html]
    ~

  • Need help with generic class with comparable type

    Hi. I'm at University, and I have some coursework to do on writing a generic class which offers ordered binary trees of items which implement the comparable interface.
    I cant get the code to compile which I have written.
    I get the error: OBTComparable.java uses unchecked or unsafe operations
    this is the more detailed information of the error when I compile with -Xlint:unchecked
    OBTComparable.java:62: warning: [unchecked] unchecked call to insert(OBTType) as
    a member of the raw type OBTComparable
    left.insert(insertValue);
    ^
    OBTComparable.java:64: warning: [unchecked] unchecked call to insert(OBTType) as
    a member of the raw type OBTComparable
    right.insert(insertValue);
    ^
    OBTComparable.java:75: warning: [unchecked] unchecked call to find(OBTType) as a
    member of the raw type OBTComparable
    return left.find(findValue);
    ^
    OBTComparable.java:77: warning: [unchecked] unchecked call to find(OBTType) as a
    member of the raw type OBTComparable
    return right.find(findValue);
    ^
    and here is my code for the class
    public class OBTComparable<OBTType extends Comparable<OBTType>>
      // A tree is either empty or not
      private boolean empty;
      // If the tree is not empty then it has
      // a value, a left and a right.
      // These are not used it empty == true
      private OBTType value;
      private OBTComparable left;
      private OBTComparable right;
      // Create an empty tree.
      public OBTComparable()
        setEmpty();
      } // OBTComparable
      // Make this tree into an empty tree.
      private void setEmpty()
        empty = true;
        value = null; // arbitrary
        left = null;
        right = null;
      } // setEmpty
      // See if this is an empty (Sub)tree.
      public boolean isEmpty()
      { return empty; }
      // Get the value which is here.
      public OBTType getValue()
      { return value; }
      // Get the left sub-tree.
      public OBTComparable getLeft()
      { return left; }
      // Get the right sub-tree.
      public OBTComparable getRight()
      { return right; }
      // Store a value at this position in the tree.
      private void setValue(OBTType requiredValue)
        if (empty)
          empty = false;
          left = new OBTComparable<OBTType>(); // Makes a new empty tree.
          right = new OBTComparable<OBTType>(); // Makes a new empty tree.
        } // if
        value = requiredValue;
      } // setValue
      // Insert a value, allowing multiple instances.
      public void insert(OBTType insertValue)
        if (empty)
          setValue(insertValue);
        else if (insertValue.compareTo(value) < 0)
          left.insert(insertValue);
        else
          right.insert(insertValue);
      } // insert
      // Find a value
      public boolean find(OBTType findValue)
        if (empty)
          return false;
        else if (findValue.equals(value))
          return true;
        else if (findValue.compareTo(value) < 0)
          return left.find(findValue);
        else
          return right.find(findValue);
      } // find
    } // OBTComparableI am unsure how to check the types of OBTType I am comparing, I know this is the error. It is the insert method and the find method that are causing it not to compile, as they require comparing one value to another. How to I put the check in the program to see if these two are of the same type so they can be compared?
    If anyone can help me with my problem that would be great!
    Sorry for the long post, I just wanted to put in all the information I know to make it easier for people to answer.
    Thanks in advance
    David

    I have good news and undecided news.
    First the good news. Your code has compiled. Those are warnings not errors. A warning is the compiler's way of saying "I understand what you are asking but maybe you didn't fully think through the consequences and I just thought I would let you know that...[something] "
    In this case it's warning you that you aren't using generics. But like I said this isn't stopping it from compiling.
    The undecided news is the complier is warning you about not using generics. Are you supposed to use generics for this assignment. My gut says no and if that's true then you have no problem. If you are supposed to use generics well then you have some more work.

  • Need help with JComponent class

    Hi,
    I'm trying to create a class that has all the characteristics of several GUI components such as JButton, JLabel, JRadioButton .... combined into one big class. But when I run the codes, the object of this new class is not visible on a frame like a JButton or a JLabel would be. Someone, please give me some hints. Thanks.
    The ButtonWrapper class extends JButton and the CheckBoxWrapper class extends JCheckBox and they both work without any problems. The GuiWrapper class (listed below) is the class that has the visibility problem when added to a container of a frame.
    import java.awt.*;
    import javax.swing.*;
    public class GuiWrapper extends JComponent{
      public GuiWrapper(String ptype, String p2, String p3) {
         if(ptype.toLowerCase() == "button"){
           ButtonWrapper b = new ButtonWrapper(p2, p3);
         if(ptype.toLowerCase() == "checkbox"){
           CheckBoxWrapper c = new CheckBoxWrapper(p2, p3);
    }

    Okay, so, for starters, I think this is a Really Bad Idea. If your developers can't handle using the API/tutorial to learn how the components work, your project will fail. This UberClass will not help in the long run. It will also almost certainly turn into a maintainence nightmare for you.
    Of course, since you're going to do it anyway... I suspect your issue lies with paintComponent. If I recall correctly, paintComponent doesn't render anything by default for a JComponent. You'll need to override paintComponent and have it invoke the renderer for the relevant child component.

  • Help with making class smaller

    Here goes... I used forte to design a gui and this gui is quite large. Its over 1400 lines already without any functionality added. Is there an easy way to make this into smaller classes. If this helps I used a desktop pane and inside I made around 9 internal frames with radio buttons and such. Any help is appreciated.

    You might take a look at your first posting; it has replies. :)

Maybe you are looking for