In Java, use the extends keyword to indicate that B inherits A. The syntax is: class B extends A { // Contents of class B }.
The syntax in Java to indicate that B inherits A
In Java, use extends
Keyword to indicate that B inherits A. The syntax is as follows:
<code class="java">class B extends A { // B 类的方法和属性 }</code>
Detailed explanation
In the above code:
is a subclass, which Inherits the
A base class.
is a base class that provides methods and properties that subclasses can use. The
keyword declares that
B inherits from
A.
Example
Let us consider a simple example:<code class="java">class Animal { protected String name; } class Dog extends Animal { public void bark() { System.out.println("汪汪!"); } }</code>
is the base class that defines the protected
name field.
is a subclass that inherits from
Animal and defines the
bark() method.
method is used to make the dog bark.
Dog class, it has access to the protected
name field in the
Animal class, and can call its own
bark() method.
The above is the detailed content of How to write B to inherit A in Java. For more information, please follow other related articles on the PHP Chinese website!