Class declaration order in java
In general, class declarations can include these components, in order:
-
A Java file can contain only one
publictop-level class. -
Modifiers such as
public,private, and a number of others that you will encounter later. (However, note that theprivatemodifier can only be applied to Nested Classes.) -
The class name, with the initial letter capitalized by convention.
-
The name of the class's parent (superclass), if any, preceded by the keyword
extends. A class can only extend (subclass) one parent. -
A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword
implements. A class can implement more than one interface. -
The class body, surrounded by braces,
{}.
Example
project/
├── Dog.java
└── Main.java
//Dog.java
// Superclass
class Animal {
public void eat() {
System.out.println("Animal is eating...");
}
}
// Interface 1
interface Pet {
void play();
}
// Interface 2
interface Trainable {
void train();
}
// Modifier: public
public class Dog extends Animal implements Pet, Trainable {
// Fields (attributes)
private String name;
private int age;
// Constructor
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
// Method from Pet interface
@Override
public void play() {
System.out.println(name + " is playing fetch!");
}
// Method from Trainable interface
@Override
public void train() {
System.out.println(name + " is learning new tricks!");
}
// Own method
public void bark() {
System.out.println("Woof!");
}
}
//Main.java
public class Main {
public static void main(String[] args) {
Dog dog = new Dog("Buddy", 3);
dog.eat();
dog.play();
dog.train();
dog.bark();
}
}