Understanding class instantiation

Given classes A, B, and C where B extends A and C extends B and where all classes implement the instance method void doIt(). A reference variable is instantiated as �A x = new B();� and then x.doIt() is executed. What version of the doIt() method is actually executed and why?
This says to me, I have just created an instance of B of class type A.
I think class B's doIt() method is the one executed because of that.
Does anyone have any insight into this?

A static method can be replaced, which can look like overriding if you don't know the difference.
For comparison
public class A {
    public static void main(String[] args) {
        new B().doit(); // prints B.doit() !
        A x = new B();
        x.doit(); // prints A.doit() !
    public static void doit() {
        System.out.println("A.doit()");
class B extends A {
    public static void doit() {
        System.out.println("B.doit()");

Similar Messages

  • Class instantiation only if allowed (ClassLoader?)

    I am implementing some runtime security checks for a project whereby I validate classes before they are allowed to be instantiated.
    Right now I use properties files and reflection to instantiate the classes, so a simple String comparison can tell me whether the class name is "allowed" to be instantiated. This can be checked just before calling Class.forName().
    Obviously, this does not keep someone from writing their own program that would instantiate my classes.
    I am trying to keep from having to go back and add a bunch of code in the constructor(s) of each class. I was thinking of subclassing ClassLoader, but have heard horror stories about them.
    Does anyone have any other ideas of how to handle this? Or perhaps some insight into ClassLoaders and whether they are easier to sub-class these days.
    thanks
    kleink

    ClassLoaders are easy to sub-class.
    The main problems people who post here seem to have with them are centered around a lack of understanding of loading classes in general.
    But I think that given your description of what you want to do, that creating a custom ClassLoader would be a good approach. Try subclassing URLClassLoader and you should not have to override too many methods (maybe just findClass()).

  • Need Help in trying to understand class objects

    I need help on understanding following problem.I have two files for that, which are as follows:
    first file
    public class Matrix extends Object {
         private int  matrixData[][];     // integer array to store integer data
         private int    rowMatrix;     // number of rows
         private int    colMatrix;     // number of columns
         public Matrix( int m, int n )
         {       /*Constructor: initializes rowMatrix and colMatrix,
              and creates a double subscripted integer array matrix
              of rowMatrix rows and colMatrixm columns. */
              rowMatrix = m;
              colMatrix = n;
              matrixData = new int[rowMatrix][colMatrix];
         public Matrix( int data[][] )
         {     /* Constructor: creates a double subscripted integer array
              and initilizes the array using values of data[][] array. */
              rowMatrix = data.length;
              colMatrix = data[0].length;
              matrixData = new int [rowMatrix][colMatrix];
              for(int i=0; i<rowMatrix; i++)
                   for(int j=0; j<colMatrix; j++)
                        matrixData[i][j] = data[i][j];
         public int getElement( int i, int j)
         {      /* returns the element at the ith row and jth column of
              this matrix. */
              return matrixData[i][j];
         public boolean setElement( int  x, int i, int j)
         {     /* sets to x the element at the ith row and jth column
              of this matrix; this method  should also check the
              consistency of i and j (i.e.,  if  i and j are in the range
              required for subscripts; only in this situation the operation
              can succeed); the method should return true if the operation
              succeeds, and should return false otherwise.
              for(i=0;i<rowMatrix;i++){
                   for(j=0;j<colMatrix;j++){
                        x = matrixData[i][j];
              if(i<rowMatrix && j<colMatrix){
                   return true;
              else{
                   return false;
         public Matrix transposeMatrix( )
         {     /*returns a reference to an object of the class Matrix,
              that contains the transpose of this matrix. */
         Verify tata;
         Matrix trans;
         //Matrix var = matrixData[rowMatrix][colMatrix];
         for(int row=0;row<rowMatrix;row++){
              for(int col=0;col<colMatrix;col++){
              matrixData[rowMatrix][colMatrix] = matrixData[colMatrix][rowMatrix];
         trans = new Matrix(matrixData);
                         return trans;
         public Matrix multipleMatrix( Matrix m )
              /*returns a reference to an object of the class Matrix,
              that contains the product of this matrix and matrix m. */
          m = new Matrix(matrixData);
              //Matrix var = matrixData[rowMatrix][colMatrix];
              for(int row=0;row<rowMatrix;row++){
                   for(int col=0;col<colMatrix;col++){
                        //trans[row][col] = getElement(row,col);
         return m;
         public int diffMatrix( Matrix m )
              /*returns the sum of the squared element-wise differences
              of this matrix and m ( reference to the formula in the description
              of assignment 5) */
         return 0;
         public String toString(  )
              /* overloads the toString in Object */
              String output = " row = " + rowMatrix + " col="+colMatrix + "\n";
              for( int i=0; i<rowMatrix; i++)
                   for( int j=0; j<colMatrix; j++)
                        output += " " + getElement(i,j) + " ";
                   output += "\n";
              return output;
    Second file
    public class Verify extends Object {
         public static void main( String args[] )
              int[][] dataA = {{1,1,1},{2,0,1},{1,2,0},{4,0,0}}; // data of A
              int[][] dataB = {{1,2,2,0},{1,0,3,0},{1,0,3,4}};   // data of B
              Matrix matrixA = new Matrix(dataA);     // matrix A
              System.out.println("Matrix A:"+matrixA);
              Matrix matrixB = new Matrix(dataB);     // matrix B
              System.out.println("Matrix B:"+matrixB);
              // Calculate the left-hand matrix
              Matrix leftFormula = (matrixA.multipleMatrix(matrixB)).transposeMatrix();
              System.out.println("Left  Side:"+leftFormula);
              // Calculate the right-hand matrix
              Matrix rightFormula = (matrixB.transposeMatrix()).multipleMatrix(matrixA.transposeMatrix());
              System.out.println("Right Side:"+rightFormula);
              // Calculate the difference between left-hand matrix and right-hand matrix
              // according to the formula in assignment description
              double diff = leftFormula.diffMatrix(rightFormula);
              if( diff < 1E-6 ) // 1E-6 is a threshold
                   System.out.println("Formula is TRUE");
              else
                   System.out.println("Formula is FALSE");
    }My basic aim is to verify the formula
    (A . B)' =B' . A' or {(A*B)tranpose = Btranspose * A transpose}Now My problem is that I have to run the verify class file and verify class file will call the matrix class and its methods when to do certain calculations (for example to find left formula it calls tranposematrix() and multipleMatrix();)
    How will I be able to get the matrix which is to be transposed in transposeMatrix method (in Matrix class)becoz in the method call there is no input for transposematrix() and only one input for multipleMatrix(matrix m).
    please peeople help me put in this.
    thanking in advance

    Please don't crosspost.
    http://forum.java.sun.com/thread.jspa?threadID=691969
    The other one is the crosspost.Okay, whatever. I'm not really concerned with which one is the original. I just view the set of threads overall as being a crosspost, and arbitrarily pick one to point others toward.
    But either way
    knightofdurham... pick one thread and post only in
    the one.Indeed. And indicate such in the other one.

  • Dynamic Class Instantiation with getDefinitionByName

    Ok so I am trying to follow the following example in
    instantiating a class dynamically:
    http://nondocs.blogspot.com/2007/04/flexhowtoinstantiate-class-from-class.html
    My AS3 code looks like this:
    var myClassName:String = event.templateName;
    //Alert.show(getDefinitionByName(myClassName).toString());
    try {
    var ClassReference:Class = getDefinitionByName(myClassName)
    as Class;
    var myInstanceObject:* = new ClassReference();
    } catch( e:Error ) {
    Alert.show("Could not instantiate the class " + myClassName
    + ". Please ensure that the class name is a valid name and that the
    Actionscript 3 class or MXML file exists within the project
    parameters.");
    return;
    However I get an error: ReferenceError: Error #1065: Variable
    OrderEdit is not defined.
    The problem is that my class is located in an altogether
    different project directory from the the calling main project (I
    include this project with these classes I am trying to dynamically
    instantiate in the project source path).
    Every example I have seen so far involves some sort of hard
    coding. I am builidng a plugin/component that I intend to use in
    various places in my site and have any general hard code is
    UNACCEPTABLE. How can I make this process COMPLETELY HARD CODE
    FREE??
    Thanks a ton!

    I am also facing the same problem, I have imported swc (flash
    created) to flex library path (Flex project >> properties
    >> Flex build path >> Library path >> add swc)
    These swc files are icons for my applications with some
    scripts (written in flash, I am using UIMovieClip). So I want to
    make it dynamic.
    I write a xml with these component name and want to create a
    object and then add that object to my canvas according to xml data.
    if I code like this:
    var myIcon:IconA = new IconA()
    canvas.addChild(myIcon); //canvas is instance of Canvas
    then its working, but if I code like
    var myDynClass:Class = getDefinitionByName("IconA") as Class
    var myIcon:* = new myDynClass()
    canvas.addChild(myIcon); //canvas is instance of Canvas
    Then its showing me same error
    Error
    Error #1065: Variable IconA is not defined.
    So, I have seen your reply but didn't get it, how can I fix
    this problem using modules. or any other way...
    Thanks,

  • Class Instantiation Issues...

    Hi,
    We are currently having issuses with a Class Interface.  Everything was working fine with it, and now it says that the class is 'not instantiated'.  If you are in SE80 or SE24 and try to test a class (e.g. CL_HRRCF_APPLICATION_CTRL), you will get a pop-up that allows you to replace generic parameter types.  Now with the non-working class, it gives a screen similar to your transport organizer, with the class name at the top with '<not instantiated>' beside it, and a list of methods below it.  This Class is being used through the web.  Also, in the title bar in 6.40, it says, 'Test Class CL_HRRCF_GLOBAL_CONTEXT: No Instance'.
    <phew>... so, has anyone else run into a problem like this, and if not, does this make enough sense?  Is there a way of instantiating a Class Interface without calling it from a program, like generation?
    Best regards,
    Kevin
    Message was edited by: Kevin Schmidt

    Hi Kevin
    I am also working on an eRecruitment 3.0 ramp-up project. What I have found is that most of the classes etc used rely on other classes etc further up the chain, they cannot be tested in isolation. Instead it is normally necessary to set a breakpoint and then log into the eRecruitment Fornt end via a web browser. The class will then be instantiated in the normal process, as you work through the system pages, and called appropriately.
    This is a BSP issue. The class in question is a basic building block of the eRecruitment BSP pages.
    Regards
    Jon Bowes [ Contract Developer ]

  • Abstract class instantiation.?

    I have an Abstract class which is extended
    My question is:
    How can the Abstract class be instantiated:
    Animal[] ref = new Animal[3];
    In Java,we cannot instantiate Abstract class,so how does this
    work
    abstract class Animal  // class is abstract
      private String name;
      public String getName(){       
           return name;
      public abstract void speak();  
    class Dog extends Animal{
          private String dogName;
          public Dog(String nm){
         this.dogName=nm;
          public void speak(){       // Implement the abstract method.
          System.out.println("Woof");
          public String getName(){   // Override default functionality.
              return dogName;
    class Cow extends Animal{
          private String cowName;
          public Cow(String nm){
          this.cowName = nm;
          public void speak(){       // Implement the abstract method.
          System.out.println("Moo");
          public String getName(){
              return cowName;
    public class AnimalArray{
      public static void main(String[] args) {
      Animal[] ref = new Animal[3]; // assign space for array
      Dog aDog = new Dog("Rover");  // makes specific objects
      Cow aCow = new Cow("Bossy"); 
      // now put them in an array
      ref[0] = aDog;
      ref[1] = aCow;
      // now dynamic method binding
      for (int x=0;x<2;++x){
           ref[x].speak();
           System.out.println(ref[x].getName());
    }

    You mean to say that now we have a handle or a reference to the
    abstract class. Right ?
    But in the
    public static Test instance () {
            return new Test () {
                public void test () {}
        }How can you say 'return new Test()' as Test is an abtract class
    and what will public void test() return as this has no body ?

  • Inner class instantiation

    Compiling the following code gives me error
    public class A
      public A()
      boolean a=true;
      class B
      { // removed syntax error "Inner"
        B()
          a = false;
      public static void main(String [] arg)
        A a = new A();
        A.B ab = a.new A.B();
        System.out.println(a);
    }The error I get is
    "A.java": Error #: 200 : '(' expected at line 30, column 21
    could somebody advise me as what I am doing wrong??

    this will compile
    public class A
    public A()
    boolean a=true;
    static class B
    { // removed syntax error "Inner"
    boolean a;
    B()
    a = false;
    public static void main(String [] arg)
    A a = new A();
    B ab = new A.B();
    System.out.println(a);
    I was talking about a member inner class. Thanx anyway. Yahya's solution worked. Interesting thing is that the way I was instantiating it is mentioned in Java Sun Certified Programmer Book in Inner classes chapter. by Syngress. But that definitely seems to be a mistake.

  • Very basic noob question about understanding class creation

    After learing some procedural scripting I just started with understanding OOP and have a problem with a basic stuff like this. Why my Try.as below is not working when I type Try(1); in the main file. Output says: Type Coercion failed: cannot convert 1 to Try
    package {
        public class Try {
            public function Try(some:Number) {
                some += 1;
                 trace (some);

    use:
    var s:Try = new Try(3);

  • Understanding class "fingerprints" with SWC files

    I'm sorry for a very poorly structured question. I just run out of English... I hope one of you guess what's the problem and can provide better words to describe it!
    I'm having hard time understanding how classes from SWC files are handled when the app is complied with Flash Builder. We have about 50 SWC files, all compiled from corresponding FLA files. Their libraries contain elements that have AS3 linkages and in the end, there are plenty of classes involved. The classes are packaged in SWC files and Flash Builder finds them just fine. Some AS3 linkages have the same name, which is OK, because they are essentially the same library elements and we don't want to have duplicates in the app. Also plenty of AS3 linkages have same base classes, which means plenty of SWC files carry those base class definitions too, but only one is really needed.
    Sometimes everything works, sometimes something breaks. It almost seems like the moon phase affects whether the end result works or not... Sometimes recompiling SWC files helps with one problem, but breaks something else. This leads me to guess, that Flash Builder selects the available classes based on the date of the SWC files? If more than one SWC files have the same class definition, Flash Builder selects the newest?
    The error we encounter, is "AS3 Error #1034: Type Coercion failed:", which is related to having one of these shared AS3 linkages (let's say SharedClass) on the timeline of a MovieClip. This means it is *not* created with the new keyword! So if SharedClass is defined in SWC1 and SWC2, maybe Flash Builder decides to use the one from SWC1. This means that elements from SWC2 that use SharedClass will use SWC1's definition of it. But for some reason this doesn't always work as it should. It helped, when I changed how AS3 references the instances declared on the timeline: "var mySharedClassObject:SharedClass" --> "var mySharedClassObject:*" but I don't understand why...
    This leads me to believe, that the SharedClass in SWC1 and SWC2 have different "fingerprints" which makes the class casting break in some situations. When I use "new" keyword, everything works, because it doesn't matter which definition will be used. But when the class is created on the timeline, it may require exact fingerprint of that class?
    Most of those cases are easily cleaned, but I'm also running into problems with some classes that have only one definition! If the AS3 linkage of SWC1 has the same base class, than AS3 linkage of SWC2, we run into the same problem. This is because both SWC1 and SWC2 contain the definition of the base class and maybe they have different fingerprints, even though our base classes are just AS3 files (no linkages).
    Does this make any sense?
    Anyone know a way to see the class name collisions and potential problems?

    If different SWC are using exactly the same class, there’s no problem. If more than one is using the same named class, and the two or more copies are different, they it’s down to the order they get compiled, and that can vary.
    Make sure that everywhere that a class has the same name, it’s identical to the other ones. Remember that MovieClips become classes too, so if you have a shared library item named “title”, and it’s different for each SWC because the graphic instead the MovieClip is different, then you’ll get big problems.
    One easy solution is to put the classes into a dedicated folder, like:
    src/com/yourname/game1/Title.as
    and:
    src/com/yourname/game2/Title.as
    instead of:
    src/com/yourname/games/Title.as
    You will end up with a lot of identical things in memory, but they have a different path, and won’t clash with each other.
    Another thing to know, if you use GetDefinitionByName(“class1”), the main document class needs to know about those classes. This will solve that problem:
    public var namedClasses:Array = [class1,class2,class3];
    Then when the compiler is doing its thing, it doesn’t go into shock when an embedded SWC is creating an instance of a class from the shared name.
    So, make sure things are truly identical, or make sure they have a different path.

  • Calling EJB facades via class instantiated via reflection?

    We are loading plugins via Java reflection. Anything instantiated via newInstance() does not appear to have access to the Local interface.
    Right now, to get to the session bean we must use the Remote interface. This is annoying due to the performance, and seems completely unnecessary when everything is operating in one JVM.
    Tests were done to print out the JNDI namespace and the local interfaces don't seem to be accessible. Any advice?

    My project consists of an EJB package and WAR. I have not had any problem calling the local facades from JSP, Servlet, or web service in the EJB package.
    Further, I can use XStream reflection and do local EJB calls.
    It baffles me why I can't do the local calls in some classes via InitialContext lookups.
    I will post test code next week.

  • Class instantiations help

    hello! my problem goes this way:
    i have 3 classes lets say a class in Canvas.java, in Player.java and in Map.java..
    private Player player;
    private Map map;
    public Canvas {
    player = new Player (this, map);
    map = new Map (this, player);
    i know this snippet returns an error in "player = new Player(this,map)"
    how am i going to implement such?
    i constructed Player and Map in Canvas because i wanted to retain their values during runtime (since both classes (Player and Map) are accessing each other)..
    i tried this:
    public Canvas {
    player = new Player (this);
    map = new Map (this, player);
    this snippet would mean i have to construct Map in the Player class like the ff..
    public Player (Canvas canvas){
    this.canvas = canvas;
    map = new Map (canvas, this);
    ..and this would mean that everytime i'll call a method in the Map class, the variables are back to their original values which in my case, i wanted to preserve the latest change in their values..
    oh my, does anybody understand my explanation? i hope so :)
    p.s.
    i think i'm stupid in java, my apology..

    does anyone know what the proper OOP way of doing this would be (if there is one) because it seems like having to call the set method after every constructor seems like a workaround (one which I've had to do myself). I was thinking maybe have a class that instantiates a map and then a player, the map is passed to the player in its constructor and inside the player's constructor you say game.getMap().setPlayer(this). Any opinions?

  • Class instantiation - and is this a pattern?

    Firstly, my apologies if my goal here is unclear. I am still learning the concepts and may perhaps have a lack of words for the appropriate terms or processes. Hopefully I can convey my meaning enough to get some feedback.
    I have a group of classes, all inheriting from a base class. My task is to add the functionality in these classes to another set of derived classes by simply creating instances of them in these classes constructor methods. To my knowledge this means the instance must take the class it's written in or (this) as it's parameter. My question is then really how should my external helper classes be written so they can be instanced in this way and is there a pattern that this idea conforms to and if so could someone explain this to me. My thanks in advance for any help, tips or directions to a good reference on this topic.

    It sounds a bit like the Strategy pattern.
    Your "helper" classes are providing various ways of performing a task on behalf of another class.
    AWT LayoutManagers implement strategies for laying out the Components in a Container. Have a look through that to see how it's done there.
    Whether your strategy classes need to take the "container" class in their constructor will depend on the functionality they provide. If their behaviour does not need to be cached then they could take a reference to the wrapper in each method call like LayoutManagers do.
    Hope this helps.

  • Dynamic Class Instantiating

    Hi,
    I need to dynamicaly instantiate classes at runtime, that is multiple instances, with different reference variables.
    I can easily intantiate a number of classes with different object variables, but i need to do it dynamically at runtime. anyone?

    I think u can better solve this by using Hashtable like data-structure.
    The key will be a String(external data like phone no.-as u said).
    The value will be the actual object which u r trying to load dynamically.
    u can load the class dynamically as follows.
    Class className=Class.forName("ClassName");
    Here class name is the name of the class whose instance u want to create dynamically.If u dont know the
    name exactly u need to use reflection.
    Object activeObject=className.newInstance();
    try this.
    -seenu_ch

  • Class instantiation through mxml - setting properties

    Hi,
    I'm trying to create a reusable component with an actionscript class.
    I'd like to be able to set a handful of the class' properties withmxml attributes. So far, I've had no success doing so.
    I've subset my problem into a separate, simplied project in an attempt to rule out any of the other parts of the real application interfering with what I'm attempting to accomplish. Unfortunately, my simplified project produces the same result.
    In my example, I'm just trying to set value of the property "myValue."  Can anyone tell me what I'm doing wrong? What am I missing?
    Thanks in advance for any help!
    Main application (TestProj.mxml)
    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
                      xmlns:s="library://ns.adobe.com/flex/spark"
                      xmlns:mx="library://ns.adobe.com/flex/mx"
                      minWidth="955" minHeight="600"
                      xmlns:pkg="pkg.*">
         <fx:Declarations>
              <!-- Place non-visual elements (e.g., services, value objects) here -->
         </fx:Declarations>
         <pkg:TestClass myvalue="some value" />
    </s:Application>
    Actionscript class (pkg\TestClass.as)
    package pkg
         import mx.controls.Alert;
         import mx.core.UIComponent;
         public class TestClass extends UIComponent
              private var _myvalue:String;
              public function TestClass()
                   Alert.show("myvalue=" + this._myvalue);     
              public function get myvalue():String
                   return _myvalue;
              public function set myvalue(value:String):void
                   _myvalue = value;

    Hi,
    The property gets set correctly, but the constructor of your class will always execute before the attributes - this is because Flex needs to create the instance and execute the c-tor before it can set the values on the instance.  Instead try something like this:
    <pkg:TestClass id="foo" myvalue="some value" initialize="{Alert.show(foot.myvalue)}" />
    This will execute the Alert.show when the component is being initialized.  If you need to put some init code in the component itself and that code relies on values set in MXML, then you can override UIComponent's public function initialize():void.
    -Evtim

  • Dynamic class instantiation

    Win2000
    SunOne Studio J2SE
    I am developing an application. I would like to instantiate classes and invoke methods dynamically, given a string containing the name of the class and/or a string containing the name of the method.
    I have the following code, and it compiles without error. However, when I run it, it throws a "ClassNotFoundException". I have read several articles that explain it as I have coded below.
    Any insights are appreciated. Thanks.
    try
    String className = "TestClass" ;
    String methodName = "OutMsg" ;
    Class testClass ;
    Object testObj ;
    Method testMethod ;
    testClass = Class.forName(className) ;
    testObj = testClass.newInstance() ;
    testMethod = testClass.getMethod(methodName, null) ;
    testMethod.invoke(testObj, null) ;
    catch (InstantiationException exc)
    System.out.println(exc) ;
    catch (ClassNotFoundException exc)
    System.out.println(exc) ;
    catch (IllegalAccessException exc)
    System.out.println(exc) ;
    catch (NoSuchMethodException exc)
    System.out.println(exc) ;
    catch (InvocationTargetException exc)
    System.out.println(exc) ;
    public class TestClass
    public void OutMsg()
    System.out.println("This is a test") ;

    You need to put complete class.
    I tried
    Class.forName("String");
    it complains that String is not found.
    But if I try
    Class.forName("java.lang.String");
    it works.
    MSN

Maybe you are looking for

  • Performance problem: Converting rows to a comma separated column using STUFF() and self join

    Hi, This might be a really dumb one to ask but I am currently working on a table that has sequential data for steps that an invoice goes through in a particular system. Here is how it looks: ID InvoiceID InvoiceSteps Timestamp 283403 0000210121_0002_

  • Why is Epson RX500 all-in-one not scanning in 10.6?

    When I upgraded to new iMac with 10.6 from older G5 with tiger, the USB RX500 worked just fine for printing and even with the print utility for ink levels and head cleaning utility.  Scanning, however, is another story. I get it that in 10.6, one now

  • Querying a date field with different masks in form and database

    Dear friends, I have a field with date format mask dd/mm/yyyy hh24:mi:ss, but the same field has date format dd/mm/yyyy inside the form which queries it. If I run this form, obviously I will query this date in dd/mm/yyyy format mask, but this date is

  • CS4 startup failure caused by MCmpgACodec.vca

    Premiere CS4 worked fine until a couple of months ago then it suddenly started to crash on startup. I recently found out that removing the latest MCmpgACodec.vca file in Premieres MediaIO/Codecs directory made Premiere launch again, but now it tries

  • Specific question for modelling an InfoCube

    Hallo experts! If I have an InfoCube which has among others two characteristics, 0MATERIAL and 0VENDOR, should i put them in one dimension or not? We have sometimes multiple vendors for one material and one material can be produced or delivered by mu