About method

Look at the code below and can you tell me why the code prints out:
SuperClass Constructor Executed
SubClass Constructor Executed
methodA in Superclass
methodB in Superclass//Why not prints out methodB in Subclass,since methodB in sub has been overriden
9
public class Superclass {
Superclass() {
System.out.println("SuperClass Constructor Executed");
private int methodB() {
System.out.println("methodB in Superclass");
return 9;
int methodA() {
System.out.println("methodA in Superclass");
return methodB();
class Subclass extends Superclass {
Subclass() {
System.out.println("SubClass Constructor Executed");
public static void main(String[] args) {
System.out.println(new Subclass().methodA());
protected int methodB() {
System.out.println("methodB in Subclass");
return 1;
}

hi,but can you tell me how java virtual machine
identify methodB() when methodA calls is the version
of Superclass,not of Subclass?I'm not sure I understand the question?
If methodB is private or "package", then at compile time the compiler knows which method is to be called. If the method is protected or public, then it can be overridden and the check must be made at runtime; It doesn't matter which class the method is declared in - it is called on an object, not on the class! (note that you get different behaviour with static methods, which you don't actually override, but hide, and do infact call on the class rather than an object).
And can you tell me whether there is an instance of
Superclass is created when an instance of Subclass is
declared and created?No. Just a single instance of Subclass is created, but to properly initialise that instance the code in the Superclass constructor must be executed.

Similar Messages

  • Question about method calling (Java 1.5.0_05)

    Imagine for example the javax.swing.border.Border hierarchy.
    I'm writing a BorderEditor for some gui builder, so I need a function that takes a Border instance and returns the Java code. Here is my first try:
    1 protected String getJavaInitializationString() {
    2     Border border = (Border)getValue();
    3     if (border == null)
    4         return "null";
    5
    6     return getCode(border);
    7 }
    8
    9 private String getCode(BevelBorder border) {...}
    10 private String getCode(EmptyBorder border) {...}
    11 private String getCode(EtchedBorder border) {...}
    12 private String getCode(LineBorder border) {...}
    13
    14 private String getCode(Border border) {
    15     throw new IllegalArgumentException("Unknown border class " + border.getClass());
    16 }This piece of code fails. Because no matter of what class is border in line 6, this call always ends in String getCode(Border border).
    So I replaced line 6 with:
    6     return getCode(border.getClass().cast(border));But with the same result. So, I try with the asSubClass() method:
    6     return getCode(Border.class.asSubClass(border.getClass()).cast(border));And the same result again! Then i try putting a concrete instance of some border, say BevelBorder:
    6     return getCode(BevelBorder.class.cast(border));Guess what! It worked! But this is like:
    6     return getCode((BevelBorder)border);And I don't want that! I want dynamic cast and correct method calling.
    After all tests, I give up and put the old trusty and nasty if..else if... else chain.
    Too bad! I'm doing some thing wrong?
    Thank in advance
    Quique.-
    PS: Sorry about my english! it's not very good! Escribo mejor en espa�ol!

    Hi, your spanish is quite good!
    getCode(...) returns the Java code for the given border.
    So getCode(BevelBorder border) returns a Java string that is something like this "new BevelBorder()".
    I want Java to resolve the method to call.
    For example: A1, A2 and A3, extends A.
    public void m(A1 a) {...}
    public void m(A2 a) {...}
    public void m(A3 a) {...}
    public void m(A a) {...}
    public void p() {
        A a = (A)getValue();
        // At this point 'a' could be instance of A1, A2 or A3.
        m(a); // I want this method call, to call the right method.
    }This did not work. So, i've used instead of m(a):
        m(a.getClass().cast(a));Didn't work either. Then:
        m(A.class.asSubClass(a.getClass()).cast(a));No luck! But:
        m(A1.class.cast(a)); // idem m((A1)a);Woks for A1!
    I don't know why m(A1.class.cast(a)) works and m(a.getClass().cast(a)) doesn't!
    thanks for replying!
    Quique

  • Details about Methods / Classes

    Hi,
    I want to get complete data about Classes & Methods(Import/Export/Exception etc) in a class. Is there any Function module or table available for the same.
    for eg if we want to get details about any particular FM then we can get it using FM FUNCTION_IMPORT_INTERFACE.
    Regards

    Hello Gaurav
    I assume you are looking for method GET_COMPONENT_SIGNATURE of class CL_OO_CLASS (CL_OO_INTERFACE).
    Regards
      Uwe

  • About method overriding and overloading

    Hi,
    What we need method overriding and overloading
    What is significance of it
    regards
    Amar

    I've read a few articles lately about people whose senses and catagories seem to "leak"
    from one to another. For example
    * Monday is red, Tuesday is yellow, etc..
    * G is red, E flat is yellow, etc...
    * Red is sour, yellow is bitter, etc...
    With that in mind...
    Overriding is spicey (garam masala), overloading is bitter (top note of asafoetida).

  • Need help about method close() in BufferedWriter Class

    Hi All,
    I'm a newbie in Java programming and I have problem regarding BufferedWriter class. I put the code snippet below.
    Sometimes I found wr.close() need a long time to be executed, around 9 seconds. For the normal case, it only needs 1 second. The transaction is same with the normal case and I found no errors in the log.
    Do you guys have any idea about this problem? What cases that can cause this problem?
    Thanks
    // Create a socket to the host
    InetAddress addr = InetAddress.getByName(shost);
    Socket socket = new Socket(shost, sport);
    // Send header
    BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"));
    data = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><request><contentcode>" + content_code +"</contentcode><msisdn>"+ orig_num +"</msisdn></request>";
    System.out.println("------------POST----------");
    wr.write("POST /" + surlname +" HTTP/1.1\r\n");
    wr.write("Host: " + shost + "\r\n");
    wr.write("Connection: close \r\n");
    wr.write("Content-type: text/xml \r\n");
    wr.write("Content-length: " + data.length() + "\r\n");
    wr.write("\r\n");
    wr.write(data);
    System.out.println("POST /" + surlname +" HTTP/1.1\r\n");
    System.out.println("Host: " + shost);
    System.out.println("Connection: close");
    System.out.println("Content-type: text/xml");
    System.out.println("Content-length: " + data.length());
    System.out.println("-------------------------");
    System.out.println("data = " + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><request><contentcode>" + content_code +"</contentcode><msisdn>"+ orig_num +"</msisdn></request>");
    wr.flush();
    // Get response
    BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    while ((linelength = rd.read(charline)) >0) {
    reply += new String(charline, 0, linelength);
    wr.close();
    rd.close();
    System.out.println("reply = " + reply);
    log.info("(New Log) reply = " + reply);

    sabre150 wrote:
    So what makes you think that not using StringBuffer is the cause of the OP's problem?Just by experience. The main cause of resource hogs in Java is large string concatenation enclosed in a loop.
    I've just made the following experience :
    public class Test {
        public static void main(String[] args) {
            new Test().execute();
        private void execute() {
            long a, b, c;
            String value = "A123456789B123456789C123456789D123456789";
            String reply = "";
            StringBuffer buffer = new StringBuffer();
            a = System.currentTimeMillis();
            for (int i = 0; i < 5000; i++) { reply += value; }
            b = System.currentTimeMillis();
            for (int i = 0; i < 5000; i++) { buffer.append(value); }
            reply = buffer.toString();
            c = System.currentTimeMillis();
            System.out.println("Duration - concatenation = " + (b-a) + " / string buffer = " + (c-b));
    }Output :
    Duration - concatenation = 21295 / string buffer = 7

  • About "method", "instance variable" and "constructor"

    Does a method need to be initialise?? if yes, how to write the code?
    for example,is it:
    public String mymethod( String args[]); ?
    public double mymethod2 (); ?
    what is the meaning of "instance variable" and "constructor"?
    Please help.....THANKS!

    Previously posted to this OP:
    Read the Java Tutorial: Learning the Java Language.
    http://java.sun.com/docs/books/tutorial/java/index.html
    � {�                                                                                                                                                                                                                                                                                                   

  • About method error

    Please, somebody would tell me where�s the error in this line...
    try {
    } catch (java.sql.SQLException e) {
    log("Exception occurred!!", e);
    error("Exception occurred!!", e);
    in bold line, I get a compile error...
    Can you help me?

    Hi
    The line should be error("Exception occurred!!"); Please check the usage of this method @http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Error.html#Error(java.lang.String,%20java.lang.Throwable)
    Thanks
    Creator

  • Question about Methods

    I was wondering why i was not getting the right output. The program should give me..
    Storing : 0
    Checking Queue...
    Printing: 0
    Storing: 1
    Checking Queue...
    Printing:1
    etc...
    but instead all I get is...
    Storing :0
    Checking Queue..
    Storing:1
    Checking Queue...
    etc..
    Here is my Code:
    import java.util.ArrayList;
    public class Problem {
         public Storage storeMe = new Storage();
         public static void main(String[] args) {
              (new Thread(new Counter())).start();
              (new Thread(new Printer())).start();
    class Storage {
         ArrayList<Integer> queue = new ArrayList<Integer>();
         public int value;
         public int getValue() {
              if (queue.size() > 0)
                   return queue.remove(0);
              else
                   return -1;
         public void storeValue(int newvalue) {
              value = newvalue;
              queue.add(value);
    class Counter extends Problem implements Runnable {
         public void run() {
              int counter = 0;
              while (true) {
                   synchronized (this) {
                        try {
                             this.wait(1000L);
                        } catch (Exception e) {
                   System.out.println("Storing : " + counter );
                   storeMe.storeValue(counter);
                   counter++;
    class Printer extends Problem implements Runnable {
         public void run() {
              while (true) {
                   synchronized (this) {
                        try {
                             this.wait(1000L);
                        } catch (Exception e) {
                   System.out.println("Checking Queue ...");
                   int num = storeMe.getValue();
                   if (num != -1)
                        System.out.println("Printing : " + num);
    }I think the problem with my code is that in the Printer class, the storeMe.getValue() method is not updated. Or more accurately, the queue is not updated.
    Can anyone shed some light on this matter?
    thanks in advance..

    thanks for that info.
    this program worked fine using static variables and methods. But now I'm trying to do it without using static modifier with the exception of the main().
    I tried checking if there was an update on queue in the Printer class by changing the code to this:
    class Printer extends Problem implements Runnable {
         public void run() {
              while (true) {
                   synchronized (this) {
                        try {
                             this.wait(1000L);
                        } catch (Exception e) {
                   System.out.println("Checking Queue ...");
                   int num = storeMe.queue.size();
                        System.out.println("Queue size: " + num);
    }and I got this output:
    Storing : 0
    Checking Queue ...
    Queue size: 0
    Checking Queue ...
    Queue size: 0
    Storing : 1
    So basically, when the Printer Class runs and tries the to get the value from the storage class, it can't because the value read was 0, there was no queue. Does this mean that I have created a wrong object of the Storage class? or is there another way to call that method without using the static modifier?
    Specifically, How do I Try to call an instance of a method with its values still intact? Let's say I want My Printer Class to access the values inputted by the Counter Class in the Storage Class.

  • About method 'write(int b)' in class 'OutputStream'

    Hello, everyone,
    In OutputStream class, there is a method called "write(int b)". In the API Specification, the explanation of this method is: Writes the specified byte to this output stream.
    I am just wondering, if the type of b is 'int', then how can it say " to write the byte to the stream"?

    Because the lower 8 bits of an int are the same value as a byte.
    -1 ==> 11111111 11111111 11111111 11111111 ==> 11111111
    0 ==> 00000000 00000000 00000000 00000000 ==> 00000000
    1 ==> 00000000 00000000 00000000 00000001 ==> 00000001
    255 ==> 00000000 00000000 00000000 11111111 ==> 11111111
    So it's essentially the same thing. Just chops off the upper 24 bits. The other thing is it's not uncommon to maintain byte values in ints for unsigned-ness, and if the method took a byte, it would require an explicit cast do to possible loss of precision, whereas a byte can be implicitly cast to an int with no alteration to the actual value represented.

  • Question about methods in a class that implements Runnable

    I have a class that contains methods that are called by other classes. I wanted it to run in its own thread (to free up the SWT GUI thread because it appeared to be blocking the GUI thread). So, I had it implement Runnable, made a run method that just waits for the thread to be stopped:
    while (StopTheThread == false)
    try
    Thread.sleep(10);
    catch (InterruptedException e)
    //System.out.println("here");
    (the thread is started in the class constructor)
    I assumed that the other methods in this class would be running in the thread and would thus not block when called, but it appears the SWT GUI thread is still blocked. Is my assumption wrong?

    powerdroid wrote:
    Oh, excellent. Thank you for this explanation. So, if the run method calls any other method in the class, those are run in the new thread, but any time a method is called from another class, it runs on the calling class' thread. Correct?Yes.
    This will work fine, in that I can have the run method do all the necessary calling of the other methods, but how can I get return values back to the original (to know the results of the process run in the new thread)?Easy: use higher-level classes than thread. Specifically those found in java.util.concurrent:
    public class MyCallable implements Callable<Foo> {
      public Foo call() {
        return SomeClass.doExpensiveCalculation();
    ExecutorService executor = Executors.newFixedThreadPool();
    Future<Foo> future = executor.submit(new MyCallable());
    // do some other stuff
    Foo result = future.get(); // get will wait until MyCallable is finished or return the value immediately when it is already done.

  • About method=get

    <form method=get> how to prevent the query stringgetting appended after click on submit button

    suma999 wrote:
    when we use method =get in form how to prevent query string from getting appended to the url on click of submit button....
    without making use of method=post==
    How do I make an omelette without breaking the egg?
    Do you understand how GET and POST work?
    People on the forum help others voluntarily, it's not their job.
    Help them help you.
    Learn how to ask questions first: http://faq.javaranch.com/java/HowToAskQuestionsOnJavaRanch
    (Yes I know it's on JavaRanch but I think it applies everywhere)
    ----------------------------------------------------------------

  • I need your help about method for 'Seperating Keypad'

    Hi~ I'm a logic user.
    I used to be a PC version logic platinum user.
    And, I'm moving to Mac OS.
    So, I bought Logic Express.
    I just want to set up 'my style keycommand'.
    Especially, seperating numbers on keyboard and keypad.
    (For example, number 1 on keyboard to 'Screen01' and number 1 on keypad to 'Rewind'.)
    My equipments are is Macbook air and USB keyboard(A1243-109key)
    I bought this extra keyboard for more convenient use at home.
    and, have done all through the Manual.
    Preference < Keycommand < option < preset < US with numeric Keypad selecting (if only 109 key) < Learn by key position & Pressing number 1 on keypad.
    But, doesn't work.
    Only with message like 'already assigned to the Screen01, will you really change?'
    In short, keypad can't be seperated.
    Can you help me?
    1. Do I have to adjust keyboard to Mac before loading Logic?
    2. Is the seperating impossible in case of Macbook + normal Keyboard?
    3. Can you guess what is the problem?
    I need your cooperation~
    Thank you~

    Please post this in Portal forum. This is Reports forum

  • Problem about method  replaceFirst();

    Hello, here is my code:
    String k="a & [ b || c ] ";
    k=k.replaceFirst("[ b || c ] ","(or(b c))");
    string like k="a & (or(b c))" is what I want to get. but when I print the result, I got "a(or(b c)) & [ b || c ] " This makes me really confused.Can anyone help me?
    Thanks a lot.

    You need to read up on which characters need to be escaped in regex.
    "[" and "]" are special charaters. They match on any one of the characters enclosed between them, so "[ b || c ]" matches on space, 'b', 'c', and '|'.
    I think the vertical bar may also be special, but I'm not sure. You probably want something like this: replaceFirst("\\[ b \\|\\| c \\]", ...) You may also want to allow for zero or more spaces, instead of specifying exactly one, but that's up to you and your requirements.

  • Best Method for Saving Data to File?

    Hi, 
    We're using labVIEW 2009 to acquire data from our instrument.  In the past we have used the "write to labview measurement file" express configuration tool to save data to a file. However we had some issues with our VI - occasionally we would lose data or column headers somewhat erratically and were never able to sort out the problem. We would like to rewrite our VI with the best possible solution. 
     Here's a summary of what we would like to do:
    Save 30 variables at a rate of roughly 1 Hz. We would like one set of column headers per file so that the data can be easily imported into labVIEW with the variable names intact. We will be collecting data continuously, so we would like to divide the data into 3-4 files per day. Ideally, the program to start new files at the same times from day to day and the filename could be configured to include the date and time/file number.
    I am hoping that users can provide a little feedback about methods that were most successful and reliable. From what I have read there are a few different ways to do this (express VI, tdms, "write to text file"). Any thoughts or relevant examples would be quite useful for us!
    Thanks for your help!

    Meg T wrote:
    Is it correct to say that in your method, the indexing results in building up the data into one large array of data before saving it to the file with the column headers and filenames appended?  If we are writing data at 1Hz for 6 hours of time, will we run into an issue being able to store all the data?
    Yes the indexing will build up one large array.  If this is a problem due to array size and memory, you will have to write more often.  You can write every second, that should not be a problem.  You should still write the column names to the file first, and have the append input set to False (or nothing wired in since the default is false).  This will create a new file with the headers only.  Then the data write has a True wired in so that the append takes place.  If running for 6 hours and gathering data once per second, your array will contain 36,006 rows of data.  I'm not sure if that would cause a memory problem or not.
    Meg T wrote:
     it also seems difficult to incorporate headers into express VI if you are writing the data continuously as a part of a loop with the "append" option.
    If you write the headers before the loop as I have shown, and use append inside the loop, you will not have problems.
    - tbob
    Inventor of the WORM Global

  • Package Error when create package via Methods onTables

    Even though I am an APEX developer for 3 years, I just found out about Methods on Tables Utility in SQL Workshop from Dan McGhan's demo. I tried to create a package for about 7 tables in one package. When the package was created, it was invalid. I tried to compile it and it produced several errors. I noticed that the UPDATE table procedure was incomplete as it did not provide parameters even though the procedure uses them.
    I was able to replicate it in APEX.ORACLE.COM.
    WORKSPACE: RGWORK
    PACKAGE: CSRSR_DML
    USER : TESTER
    Password: test123
    Is this a bug? Is there a workaround? Did anyone else experience similar outcome?
    APEX 4.1
    Oracle 10g Rel 2
    Robert
    http://apexjscss.blogspot.com

    sect55 wrote:
    Come on APEX team and gurus, please help....As far as this "guru" is concerned, it's not something I'd ever use:
    http://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:672724700346558185
    http://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:25405782527721
    Given Tom's well-known opposition to this approach, I was more than a little surprised when this appeared in APEX as he also appears to have close links to the APEX team. I'd really rather have seen development effort invested elsewhere.
    I'd definitely advocate building applications based on PL/SQL APIs, just not on table-centric, row-by-row ones...
    I tried to create a package for about 7 tables in one package.Why?
    One of the main purposes of packages is to modularize an application. Sticking methods for all of the entities in one package defeats this and makes development, testing and maintenance harder. If you must use the flawed TAPI concept, create a separate API for each table&mdash;at most only combine those where there exist mandatory dependencies, e.g. an <tt>order</tt> package with methods for <tt>orders</tt> and <tt>order_items</tt>.
    As to the immediate problem, it appears to be due to the lack of primary key definitions on some of your tables. This means the generator is unable to identify which columns to use as unique row identifiers.

Maybe you are looking for