| René Nyffenegger's collection of things on the web | |
|
René Nyffenegger on Oracle - Most wanted - Feedback
|
classes in JAVA | ||
Elements of a className of class
A class has a name. In the following example, the name of the class
is name_exp. The name of the class must follow the rules of valid identifiers.
class name_exp {
// more elements, such as
// constructors
// methods
// variable
}
Constructor
The constructor is used when a new object is created. It's purpose is to initialize the newly created
object.
If a class does not explicitly specify a constructor, the compiler supplies a default constructor that looks like:
class_name() {}
Methodsclass class_name { public void do_something () { /* here is the code that does something */ } public static void some_class_method() { /* here is the code that does something */ } }
A method must follow the rules of valid identifiers.
A static method is also called a class method
Variablesclass class_name { private int[] some_array; private boolean is_valid; private static int counter; }
A variable must follow the rules of valid identifiers.
Nested classes vs top level classes
A class is either a top level class (also known as top-level package member classes) or a nested class.
Top level package member classes (or interfaces)package SomePackage; class ATopLevelClass { // The class is not nested in another class } Top level nested classes (or interfaces)
class FooBar {
static TopLevelNestedClass {
// Top level nested class because within a top level class and static
static AnotherTopLevelNestedClass {
// Top level nested class because within a top level class and static
// top level nested classes are considered top level although they're nested
}
}
}
Although a nested class, it is also considered a top level class.
Non-static inner classes
A non-static inner class cannot have static members.
class FooBar {
public class NonStaticInnerClass {
private int i_;
public void do_something() { }
// static float f_; // ILLEGAL
}
}
A non-static inner class must be associated with an existing object of the enclosing class.
Local classes
Local classes are defined in a block.
Anonymous classes
interface IFoo {
void msg();
}
class Foo implements IFoo {
public void msg() {System.out.println("The message is: " + s() );}
protected String s() {return "Bar";}
}
public class A {
public static void main(String[] args) {
Foo foo = new Foo() {
protected String s() {return "anonymous";}
};
foo.msg();
}
}
|