user1084821
user1084821

Reputation: 1

Java CLASS METHODS

CLASS METHODS question: According to D. Flanagan, Java in a Nutshell, 5 edn, pg 102-103, CLASS methods are allowed to be invoked FROM EITHER i) code existing OUTSIDE of the method's class, the standard paradigm, OR from ii) INSIDE the class itself which defines the class method. Here, I believe the standard oo programming paradigm is to put System.out.println statements in a class T method prt(), and then declare a new T object, t1 say, with t1.prt() method called from the outside class, main:

class T {
    int x = 4, y = 5;

    public static void prt(int x0, int y0) {

        System.out.println("T class ending: x= " + x0 + ", y=" + y0);
    }
    // <---- this is where an extra statement gets inserted 
}

class S extends T {
    int m = 10;
    int n = m + x + y;

    public void prs() {
        System.out.println("S subclass ending: m = " + m + ", n=" + n);
    }
}

public class A {
    public static void main(String[] args) {

        System.out.println("****Program start");
        System.out.print("main method: ");
        T t1 = new T();
        t1.prt(3, 4);
        S s1 = new S();
        System.out.println(s1.m);
        System.out.println(s1.n);
        s1.prs();
        System.out.println("****Program ending");
    }
}

However, when I demand to do what Flanagan states is possible, to invoke a class method FROM WITHIN the class T in which the CLASS METHOD is defined, I get the original compilation error again, that "an identifier is expected." That is, inserting the following statement at the end of class T code, as shown above(*), gives a compiLe error:

T.prt(3,4);

Why this is an error? My question asks about general CLASS METHODS, not a special class method, namely a constructor, though the Java reference text I'm citing does deal with CLASS METHODS in general. Am I missing something obvious? My sincerest gratitude, Richard Pan in Newark

Upvotes: 0

Views: 346

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533472

That is, inserting the following statement at the end of class T code, as shown above(*), gives a compiLe error:

You can only write code inside methods. Outside methods you can only define fields, which is what it is expecting.

Am I missing something obvious?

I used my IDE to format the code (This was one key press btw) and the problem became obvious. If you don't format your code it make it harder to read and understand.

Upvotes: 1

Related Questions