MsA
MsA

Reputation: 2979

Understanding java class file

I came across this question :

How can we identify whether a compilation unit is class or interface from a .class file?

The answer given was "from java source file header", with explanation

The Java source file contains a header that declares the type of class or interface, its visibility with respect to other classes, its name and any superclass it may extend, or interface it implements.

But I didn't find anything explaining how source file header dictates class or interface in any standard documentation. Wikipedia says following about the magic number (which I found to be relevant) in the class file:

CAFEBABE became the class file format, and CAFEDEAD was the persistent object format.

Can someone point me to document explaining in detail how class file tells whether it's for class or interface along with other details of class file?

Upvotes: 0

Views: 971

Answers (2)

Andreas
Andreas

Reputation: 159260

How can we identify whether a compilation unit is class or interface from a .class file?

According to Chapter 4. The class File Format of the Java Virtual Machine Specification:

A class file consists of a single ClassFile structure:

ClassFile {
    u4             magic;
    u2             minor_version;
    u2             major_version;
    u2             constant_pool_count;
    cp_info        constant_pool[constant_pool_count-1];
    u2             access_flags;
    . . .

And:

The value of the access_flags item is a mask of flags used to denote access permissions to and properties of this class or interface. The interpretation of each flag, when set, is:

Flag Name      Value   Interpretation
ACC_PUBLIC     0x0001  Declared public; may be accessed from outside its package.
ACC_FINAL      0x0010  Declared final; no subclasses allowed.
ACC_SUPER      0x0020  Treat superclass methods specially when invoked by the invokespecial instruction.
ACC_INTERFACE  0x0200  Is an interface, not a class.
. . .

So if the 2-byte access_flags value has bit 9 set, then it is an interface, otherwise it's a class.

Upvotes: 3

Atahan Atay
Atahan Atay

Reputation: 363

For example;

class a {
    ...
}

interface a {
    ...
}

Also, you can extend a class, or implement an interface.

When you extend a class you can use another classes all functions, and it writes like that:

class a extends JFrame {
    a() {
        setVisible(true); //a method for jframe
    }
}

When you use an interface you must implement it:

class b implements KeyListener {
    public void keyPressed(KeyEvent e) { 

    }

    public void keyReleased(KeyEvent e) { 

    }

    public void keyTyped(KeyEvent e) {

    }

}

Upvotes: 0

Related Questions