In Java, superclass is the parent class of a class, specified by the extends keyword. It provides code reuse, organization and polymorphism, allowing subclasses to access superclass members using the super keyword. In overriding, the subclass reimplements the inherited method, whereas in overriding, the subclass adds or modifies functionality while retaining the original implementation.
Superclass in Java
In Java, superclass is the parent class of a class. It defines the properties and methods that subclasses inherit.
Why use superclass?
How to define superclass
You can specify a superclass using the extends keyword in the class definition as follows:
<code class="java">class Subclass extends Superclass { // 子类代码 }</code>
Accessing superclass members
Subclasses can use the super keyword to access members of their superclass. There are the following two methods:
super.methodName()
super.attributeName
##Override vs. Rewrite
Example
Suppose we have anAnimal superclass that defines a
speak() method:
<code class="java">class Animal { public void speak() { System.out.println("Animal speaks!"); } }</code>
Dog subclass that inherits from
Animal and overrides the
speak() method:
<code class="java">class Dog extends Animal { @Override public void speak() { System.out.println("Dog barks!"); } }</code>
speak() method is overridden, which means that the subclass method completely replaces the parent class method.
The above is the detailed content of What does superclass mean in java. For more information, please follow other related articles on the PHP Chinese website!