Inheritance of Classes
public class fruit{
public double weight;
public void info () {
System.out.println ("fruit" +weight);
}
}
public class Apple extends fruit{
public static void Main (string[] args) {
Create an Apple Object
Apple apple=new Apple ();
The Apple object itself does not have a weight member variable
Because Apple's parent class has weight member variables, you can also access the weight member variables of Apple objects
a.weight=90;
Call the info () method of an Apple object
A.info ();
}
}
public class bird{
Fly () method for the bird class
public void Fly () {
System.out.println ("Fly");
}
}
public class Os extends bird{
Overriding the Fly () method of the bird class
public void Fly () {
System.out.println ("Fly1");
}
public static void Main (string[] args) {
Creating an OS Object
OS o=new os ();
Execute the Fly () method of the OS object
O.fly ();
}
}
You can use super (overridden by an instance method, or the parent class name (which is overridden by a class method) as the caller to invoke the overridden method
If the parent method has private access, the method is hidden from its subclasses, so the subclass cannot access the method
Class animal{
private void Beat () {
System.out.println ("Beat");
}
public void Breathe () {
Beat ();
System.out.println ("Breathe");
}
}
Inherit animal, directly reuse the breathe () method of the parent class
Public Bird extends animal{
public void Fly () {
System.out.println ("Fly");
}
}
Inherit animal, directly reuse the breathe () method of the parent class
Public Wolf extends animal{
public void Run () {
System.out.println ("Run");
}
}
public class inherittest{
public static void Main (string[] args) {
Bird b=new Bird ();
B.breathe ();
B.fly ();
Wolf W=new Wolf ();
W.breathe ();
W.run ();
}
}
Class animal{
private void Beat () {
System.out.println ("Beat");
}
}
public void Breath () {
Beat ();
System.out.println ("Breathe");
}
}
Class bird{
Combine the original parent class into the original subclass as a composition of the subclass
Private Animal A;
Public Bird (Animal a) {
This.a=a;
}
Redefine one's own breathe () method
public void Breathe () {
Direct multiplexing of the Breathe () method provided by the animal to implement the bird Breathe () method
A.breathe ();
}
public void Fly () {
System.out.println ("Fly");
}
}
Class wolf{
...
}
public class compositetest{
public static void Main (string[] args) {
You need to display the object that you created the group at
Aniaml animal=new animal ();
Bird b=new Bird (a);
B.breathe ();
B.fly ();
You need to display the object that you created the group at
Aniaml animal1=new Animal ();
Wolf W=new Wolf (ANIMAL1);
W.breathe ();
W.run ();
}
}
Inheritance and composition of classes