Inner Class extending the outer class

Could anyone explain this code to me? It can compile and run. Could anyone tell me what the class Main.Inner.Inner is? What members does it consists of? How the compiler manage to build such a class?
public class Main {
    public static class Inner extends Main {
    public static void main(String[] args) {
        System.out.println("Hello, world.");
}

By the way, it's not really an inner class, because it's static. It's just a nested class.
You might want to have a nested class extend its enclosing class if, maybe, you wanted to delegate to subclasses and didn't want to create a lot of extra source code files, which might make sense if the nested subclasses were really small.
public abstract class Animal {
  public abstract void makeSound();
  private Animal() {} // can't be directly instantiated
  private static class Dog extends Animal {
    public void makeSound() { System.out.println("woof"); }
  private static class Cat extends Animal {
    public void makeSound() { System.out.println("meow"); }
  private static class Zebra extends Animal {
    public void makeSound() { System.out.println("i am a zebra"); }
  public static Animal get(String desc) {
    if ("fetches sticks".equals(desc)) {
      return new Dog();
    if ("hunts mice".equals(desc)) {
      return new Cat();
    if ("stripey horse".equals(desc)) {
      return new Zebra();
    return null;
public class AnimalTest {
  public static void main(String... argv) {
    Animal a = Animal.get("fetches sticks");
    a.makeSound();
}

Similar Messages

  • Confused about extending the Sprite class

    Howdy --
    I'm learning object oriented programming with ActionScript and am confused about the Sprite class and OO in general.
    My understanding is that the Sprite class allows you to group a set of objects together so that you can manipulate all of the objects simultaneously.
    I've been exploring the Open Flash Chart code and notice that the main class extends the Sprite class:
    public class Base extends Sprite {
    What does this enable you to do?
    Also, on a related note, how do I draw, say, a line once I've extended it?
    Without extending Sprite I could write:
    var graphContainer:Sprite = new Sprite();
    var newLine:Graphics = graphContainer.graphics;
    And it would work fine. Once I extend the Sprite class, I'm lost. How do I modify that code so that it still draws a line? I tried:
    var newLine:Graphics = this.graphics;
    My understanding is that since I'm extending the Sprite class, I should still be able to call its graphics method (or property? I have no idea). But, it yells at me, saying "1046: Type was not found or was not a compile-time constant: Graphics.

    Thanks -- that helped get rid of the error, I really appreciate it.
    Alas, I am still confused about the extended Sprite class.
    Here's my code so far. I want to draw an x-axis:
    package charts {
        import flash.display.Sprite;
        import flash.display.Graphics;
        public class Chart extends Sprite {
            // Attributes
            public var chartName:String;
            // Constructor
            public function Chart(width:Number, height:Number) {
                this.width = width;
                this.height = height;
            // Methods
            public function render() {
                drawAxis();
            public function drawAxis() {
                var newLine:Graphics = this.graphics;
                newLine.lineStyle(1, 0x000000);
                newLine.moveTo(0, 100);
                newLine.lineTo(100, 100);
    I instantiate Chart by saying var myChart:Chart = new Chart(); then I say myChart.render(); hoping that it will draw the axis, but nothing happens.
    I know I need the addChild method somewhere in here but I can't figure out where or what the parameter is, which goes back to my confusion regarding the extended Sprite class.
    I'll get this eventually =)

  • How to override a method in an inner class of the super class

    I have a rather horribly written class, which I need to adapt. I could simply do this if I could override a method in one of it's inner classes. My plan then was to extend the original class, and override the method in question. But here I am struggling.
    The code below is representative of my situation.
    public class ClassA
       ValueChecks vc = null;
       /** Creates a new instance of Main */
       public ClassA()
          System.out.println("ClassA Constructor");
          vc = new ValueChecks();
          vc.checkMaximum();
         // I want this to call the overridden method, but it does not, it seems to call
         // the method in this class. probably because vc belongs to this class
          this.vc.checkMinimum();
          this.myMethod();
       protected void myMethod()
          System.out.println("myMethod(SUPER)");
       protected class ValueChecks
          protected boolean checkMinimum()
             System.out.println("ValueChecks.checkMinimum (SUPER)");
             return true;
          protected boolean checkMaximum()
             return false;
    }I have extended ClassA, call it ClassASub, and it is this Class which I instantiate. The constructor in ClassASub obviously calls the constructor in ClassA. I want to override the checkMinimum() method in ValueChecks, but the above code always calls the method in ClassA. The ClassASub code looks like this
    public class ClassASub extends ClassA
       public ClassAInner cias;
       /** Creates a new instance of Main */
       public ClassASub()
          System.out.println("ClassASub Constructor");
       protected void myMethod()
          System.out.println("myMethod(SUB)");
       protected class ValueChecks extends ClassA.ValueChecks
          protected boolean checkMinimum()
             System.out.println("ValueChecks.checkMinimum (SUB)");
             return true;
    }The method myMethod seems to be suitably overridden, but I cannot override the checkMinimum() method.
    I think this is a stupid problem to do with how the ValueChecks class is instantiated. I think I need to create an instance of ValueChecks in ClassASub, and pass a reference to it into ClassA. But this will upset the way ClassA works. Could somebody enlighten me please.

    vc = new ValueChecks();vc is a ValueChecks object. No matter whether you subclass ValueChecks or not, vc is always of this type, per this line of code.
    // I want this to call the overridden method, but it does not, it seems to > call
    // the method in this class. probably because vc belongs to this class
    this.vc.checkMinimum();No, it's because again vc references a ValueChecks object, because it was created as such.
    And when I say ValueChecks, I mean the original class, not the one you tried to create by the same name, attempting to override the original.

  • EXTENDING the string class

    ok, i know extending the string class is illegal because it's final, but i want to make an advanced string class that basically "extends" the string class and i've seen online this can be done through wrapper classes and/or composition, but i'm lost
    here is my sample code that is coming up with numerous compile time errors due to the fact that when i declare a new AdvString object, it doesn't inherit the basic string features (note: Add is a method that can add a character to a specified location in a string)
    class AdvString
         private String s;
         public AdvString(String s)
              this.s = s;
         public void Add(int pos, char ch)
              int this_len = (this.length()) + 1;
              int i;
              for(i=0;i<(this_len);i++)
                   if(pos == i)
                        this = this + ch;
                   else if(pos < i)
                        this = this + this.charAt(i-1);
                   else
                        this = this + this.charAt(i);
         public static void main(String[] args)
              AdvString s1;
              s1 = new AdvString("hello");
              char c = 'x';
              int i = 3;
              s1.Add(i,c);
              //s2 = Add(s1,i,c);
              //String s2_reversed = Reverse(s2);     
              System.out.println("s1 is: " + s1);
    any tips?

    see REString at,
    http://www.geocities.com/rmlchan/mt.html
    you will have to replicate all the String methods you are interested in, and just forward it to the String instance stored in REString or the like. it is like a conduit class and just passes most processing to the 'real' string. maybe a facade pattern.

  • Can we extend the Throwable class instead of Exception Class??

    Hi all..
    Can we extend the Throwable class instead of Exception Class while creating our own custom Exception?If not Why?
    Please give your valuble advices..
    Ramesh.

    I don't want to hijack the thread here, but in a conversational tone...on a related note.. I've thought about this too a bit and wondered if there are some recommended practices about catching and handling Throwable in certain applications. Like the other day I was debugging a web application that was triggering a 500. The only way I could find the problem in an error stack was to write code to catch Throwable, log the stack, and then re-throw it. I considered it "debug" code, and once I solved the problem I took the code out because, my understanding is, we don't want to be handling runtime problems... or do we? Should I have a catch clause for Throwable in my servlet and then pass the message to ServletException?
    So along with the OP question, are there separate defined occasions when we should or should not handle Throwable? Or does it just all depend on circumstance?

  • Extending the Thread class

    i would like to do that
    1) One thread displays "ABC" every 2 second;
    2) The other thread displays DEF every 5 seconds;
    i need to create the threads by extending the Thread class ...
    thank you for your help ,
                public class Thread1 extends Thread {
              public Thread1(String s ) {
                   super (s);
              public void run() {
                   for ( int i=0; i<5; i++ ) {
                        System.out.println(getName());
                        try {
                           sleep ((long) 5000);
                        } catch (InterruptedException e ) {
                           /* do nothing */
              public static void main (String args[]) {
                   new Thread1 ("ABC").start();
                   new Thread1 ("DEF").start();
         }     

    I think he has been told to use the Thread class by the sounds of it.
    public class Thread1 extends Thread {
         public Thread1(String s ) {
              super (s);
         public void run() {
              for ( int i=0; i<5; i++ ) {
                   System.out.println(getName());
                   try {
                      sleep (getName().equals("ABC")? 5000 : 2000); //If you don't understand this then Google for "Java ternary operator"
                   } catch (InterruptedException e ) {
                      /* do nothing */
         public static void main (String args[]) {
              new Thread1 ("ABC").start();
              new Thread1 ("DEF").start();
    }

  • Extending the Dialog Class

    Hey, I'm trying to extend the Dialog class into something called a DialogErrorBox, which is just what it sounds like: a dialog box specifically for telling the user about errors it encounters. Here's the code:
    import java.awt.*;
    import java.awt.event.*;
    class DialogErrorBox extends Dialog implements ActionListener {
         public DialogErrorBox (Frame parent) {
        ...//modified to give a vague error message
         }//end constructor
    public DialogErrorBox (Frame parent, String title, String message) {
        ...//worked as a function in my program
         }//end constructor
    public void actionPerformed (ActionEvent evt) {
              this.dispose();
    }The compiling error I recieve at both constructors is:
    ...cannot resolve symbol
    symbol  : constructor Dialog  ()
    location: class java.awt.Dialog
            public DialogErrorBox2 (Frame parent, String title, String message) {I can't figure out why this error would happen. I've made a class extending Frame(Frame and Dialog both extend Window) that looks almost exactly the same and it has no errors.
    Help would be much appreciated.

A: Extending the Dialog Class

This is a short and spotty explanation, to get the full skinny you might read pages 69 and 70 of The Java Programming Language 3rd Edition, Gosling, et. al.
If you don't use the superclass's constructor or one your own as the first executable statement , the superclass's no arg constructor gets called. This means that super() will get called automagically! I don't believe that Dialog has a no arg constructor, so you are forced to do something.
You could also do something like this:
public DialogErrorBox(Frame frame, String title) {
   this(frame, title, true);
}Now the two argument constructor invokes the three arument constructor with a default value of true.
Do you see why this must happen?

This is a short and spotty explanation, to get the full skinny you might read pages 69 and 70 of The Java Programming Language 3rd Edition, Gosling, et. al.
If you don't use the superclass's constructor or one your own as the first executable statement , the superclass's no arg constructor gets called. This means that super() will get called automagically! I don't believe that Dialog has a no arg constructor, so you are forced to do something.
You could also do something like this:
public DialogErrorBox(Frame frame, String title) {
   this(frame, title, true);
}Now the two argument constructor invokes the three arument constructor with a default value of true.
Do you see why this must happen?

  • 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;
    }~

  • How can I extend the Vector class?

    Hi All,
    I'm trying to extend the Vector class so I can get add a .remove(item:T) method to the class.  I've tried this:
    public class VectorCollection extends Vector.<T>
    That gives me the compile error "1017: The definition of base class Vector was not found"
    So then I tried:
    public class VectorCollection extends Vector
    Which gives me the compile error "1016: Base class is final."
    There must be some way to extend the Vector class, though, as on the Vector's official docs page it says:
    Note: To override this method in a subclass of Vector, use ...args for the parameters, as this example shows:
         public override function splice(...args) {
           // your statements here
    So there must be a way to extend the Vector class.  What am I doing wrong?

    No. AS3 doesn't currently have full support for generic types; Vector.<T> was added in an ad-hoc ("ad-hack"?) way. We are considering adding full support in a future version of ActionScript.
    Gordon Smith
    Adobe Flex SDK Team

  • Explicitly extending the Object class

    Hi Everyone,
    I am aware that every object that is running inside a JVM inherits from class Object implicitly. Recently I have come across some code that explicitly extends the Object class, is there any advantage in doing this, please see the code snippet below:
    public class MyClass extends Object{}Thanks heaps for your assistance.
    Regards
    Davo

    I've even seen a
    method that was declared "throws NullPointerException"shouldn't it have been "throws java.lang.NullPointerException" ...
    - I almost cried. Yes, thats truly a terrible habit :(
    a distant cousin of that habit is one I have noticed where the developer
    is totally unable to name anything appropriately..
    to print some things to the screen: "loadData"
    to print things to screen again: "getInformation" *(note: did not 'return' anything).
    ... :(

  • Extend the String Class

    Is there a way to extend the string class? I know it's final, if i make my class final too would that work? I want to add some functionality to the string class, but I wanna be able to do concatination with the + operator and stuff like that. That's special to the String class.
    Any help would be great.
    Thanks.
    Joe

    Well, put your mind at easy with the fact that being
    able to use the '+' operator on Strings is a design
    flaw in Java. At least from a purist point of view...And from a pragmatist's point of view, it's a reasonable compromise, the benefit of which outweighs the downside. This is consistent with Java's goal as a good general-purpose language. It's not intended to be pure OO or pure anything else.

  • I need help extending the MovieClip class

    I want to add a property to the MovieClip class. I just have a bunch of MovieClips that are placed on the stage by reading an XML file and creating lots of clips according to the information in them. Now, I need to know which MovieClips were created below previous clips, and I figure that the easiest way to do so would be by extending the MovieClip class and add an order property.
    I have some problems though: I don't know how to set or get this order property within the main clip, I don't know how to place this clip within my movie, and I don't know how to create them dynamically (do I just do something like var myNewObjectOfExtendedClass : myExtendedClassName = new myExtendedClassName?)
    This is the code I have on my extended class, called Expando.as:
    class Expando extends MovieClip {
    private var _order:Number;
    public function get order():Number {
    return _order;
    public function set order(nOrder:Number):Void {
    _order = nOrder;

    You mean the Tree component?
    My concern with the Tree component (at least the AS2 version) is that I don't see a way to have each node in the Tree have different hit areas with different outcomes.
    The tree that I build must have up to 7 levels within each main branch, and not all of them behave the same way. In some branches, clicking the icon next to the label will have a completely different outcome than clicking on the label, which may or may not return a function. Each of those sublevels also need to support different icons, depending on what information is represented by it.
    Sample:
    • Reminders
    My Reminders
    Manual Reminders
    Escalated Reminders
    • Cases
    Name Actions < ---- this is where the problem begins. Clicking on the icon where the bullet should be should do something different than clicking on the name, which should do something different than clicking on the word ActionsThis is information about that referral that includes who referred them, the date of the referral, their full address. This information usually takes up 2 lines, sometimes 3
    Assignment   <------- you can only open see these leaves if you click on the bullet icon for the previous node; you can't open this by clicking on the text.
    Eligibility
    Etc., depending on what information has been appended
    • Suppliers
    Anyway, if the Tree Component can indeed support these features, I'd like to know where to find information about it please
    In my search for that information, I concluded that I'd probably be better served by building my own MovieClip that can handle these requirements. I did have a working Tree component pretty quickly as I started this project, but then I got more familiar with the app that I'm building the training for and noticed these requirements.
    Of course, maybe all these features are supported by the AS3 Tree component. The problem is that I'm a lot worse with AS3 than I am with AS2 heh.

  • Inner class access to outer class variables

    class X extends JTextField {
    int variable_a;
    public X() {
    setDocument(
    new PlainDocument() {
    //here i need access to variable_a
    i don't want to make variable_a a static member though, so does anyone know how to do it?

    Generally, you can reference your variable_a just as you would any other variable except if your inner class also defines a variable_a. However, to produce a reference to the enclosing outer class object you write "OuterClassName.this". So, to get to your variable I think you would write "X.this.variable_a". I hope this helps.

  • Extending the Socket class...

    I need some help. The class below, SimpleSocket, extends the built-in
    Socket class and adds two methods to it. These methods are meant to
    make the class a bit more user-frienly but simplifying the reading-from
    and writing-to a Socket object. Here it is:
    bq. import java.net.*; \\ import java.io.*; \\ public class SimpleSocket extends Socket { \\ BufferedReader in; \\ PrintWriter out; \\ public void println(String line) throws IOException \\ { \\ if (out == null) { out = new PrintWriter(this.getOutputStream(), true); } \\ out.println(line); \\ } \\ public String readLine() throws IOException \\ { \\ if (in == null) { in = new BufferedReader( new InputStreamReader(this.getInputStream())); } \\ return in.readLine(); \\ } \\ }
    If I want to create a new SimpleSocket, it's easy - I can instantiate it like a normal Socket:
    bq. SimpleSocket socket = new SimpleSocket(host,port); // assume host & port have been defined
    Now, lets say I have a Socket object that I didn't created - for
    example, a Socket returned from the ServerSocket class - like this:
    bq. ServerSocket serverSocket = new ServerSocket(port); \\ Socket clientSocket = serverSocket.accept(); // returns the socket for communicating with a client
    Now that I have a regular Socket object, is there some what to
    "upgrade" it to a SimpleSocket? Something like this: (pseudocode):
    bq. clientSocket.setClass(SimpleSocket); // this is pseudocode
    Or, could I make a SimpleSocket constructor that accepted a Socket
    object as a parameter and then used it instead of creating a new
    object? Like this: (psuedocode):
    bq. public SimpleSocket(Socket S) \\ { \\ super = S; // this is pseudocode \\ }
    Any ideas would be greatly appreciated.
    Lindsay
    Edited by: lindsayvine on Sep 15, 2007 10:50 PM

    lindsayvine wrote:
    Ok, this makes sense and this is what I will probably do. However, there are three limitations to this method that I don't like:
    1. I would like to be able to pass the SimpleSocket object around as a normal Socket. I would like SimpleSocket to be castable to a Socket.Would you? What for? Are you sure? Would input and output streams not be better objects to pass around? You might well have the requirement you say you have, but I say it's an assumption to be challenged, at the very least
    2. I would like every method of the Socket object to be available - this would means that I have to rewrite out every method in SimpleSocket - instead of just saying "hey SimpleSocket, you should have every method Socket has"Yep. But using inheritance simply to avoid some typing is no reason to use inheritance. This is all providing that you need to have every method available. Remember, if any dependent code needs the underlying socket object, your interface can always expose it
    3. If I do write out every method, but then the Socket object gets new methods in future versions of Java, I will have to add the new ones.Likewise, in the case of such a change to java.net.Socket, your subclass has a very real chance of breaking. Again, consider if your code needs to exactly replicate everything a Socket does
    Can you think of any way around these problems?
    Sure. Re-think your design

  • Error Extending the OAEntityImpl class when creating a BC4J  Entity Object

    I have created an EO based on an Oracle Apps table and extended the OAEntityDefImpl, OAEntityCache and OAEntityImpl classes as specified in the OA Framework Developers Guide when creating EO's via the BC4J wizard.
    When I build my Business Components package I recive an error stating that the Impl class should be declared abstract.
    Error(14,8): class oracle.apps.xxtpc.arinvoices.schema.TpcApInvoicesEO2Impl should be declared abstract; it does not define method setLastUpdateLogin(oracle.jbo.domain.Number) in class oracle.apps.fnd.framework.server.OAEntityImpl
    When I modify this class to declare it abstract and then try to test (via the AM test function) the VO that I created based on this EO - I receive an oracle.jbo.RowCreateException: JBO-25017.
    Do you think that this has anything to do with modifying the Impl class to make it abstract? I can create another VO against the same table by creating a SQL statement against it and not basing it off of the EO and this VO will run correctly via the AM tester.
    Thanks,
    Chris
    oracle.jbo.RowCreateException: JBO-25017: Error while creating a new entity row for TpcApInvoicesEO.
         at oracle.jbo.server.EntityDefImpl.createBlankInstance(EntityDefImpl.java:1054)
         at oracle.jbo.server.ViewRowImpl.createMissingEntities(ViewRowImpl.java:1532)
         at oracle.jbo.server.ViewRowImpl.init(ViewRowImpl.java:236)
         at oracle.jbo.server.ViewDefImpl.createBlankInstance(ViewDefImpl.java:1050)
         at oracle.jbo.server.ViewDefImpl.createInstanceFromResultSet(ViewDefImpl.java:1007)
         at oracle.jbo.server.ViewObjectImpl.createRowFromResultSet(ViewObjectImpl.java:2643)

    The problem was that there were no audit columns in the table that I was querying.

  • Maybe you are looking for

    • Using IMAC (Intel) monitor for external machine

      I recently bought an Intel 24" IMAC , which is mahvelous, EXCEPT, (shockingly enough!) it won't run all my beloved system 9 aps. Even worse, it apparently won't run any PhotoShop, except for the latest & greate$t version. Is there any way that I can

    • Task not coming in Open Provisioning Task when Request is raised(OIM 9i)

      Hi When ever i am assigning the task to group that task is not getting updated in the open provisioning tasks. I i assign the task to xelsysadm instead of the group i am able to see the task in open provisioning tasks. I thought its permission issue

    • Extract Cube data for all entries of an internal table

      Hi I want to fetch the data from the cube for all entries of another internal table. Scenario : Fetching the COMPANY_CODE and DATE into an internal table and for those company codes and Dates, I have to fetch the records of the Cube., I am using the

    • Table cast PL/SQL: ORA-00902: invalid datatype

      I m getting PL/SQL: ORA-00902: invalid datatype error in OPEN pPymtCur FOR SELECT * FROM TABLE(CAST( up_gap_tra_reports.myArray AS traArray)); in my package up_gap_tra_reports. CREATE OR REPLACE PACKAGE GAPSDVEL.up_gap_tra_reports AS TYPE traRecord I

    • Cancelling an application that is in the process of downloading

      I have been downloading many applications, and there are a few that are so large that require WI-FI to download. I was in a restaurant that had free wi-fi and started to download a couple of those apps. However, I had to leave before they were finish