As a language for object-oriented development, code reuse is one of the notable features of Java. The reuse of Java code is inherited, combined and represented by three specific representations, the following one by one ways.
The first approach is to implement code reuse by creating a new class based on the type of the existing class, which is called inheritance. When we create a new class, we always inherit such or such a parent class, and the implicit parent class is the object class.
public class A {
int A;
public A (int a) {
This.a=a;
SYSTEM.OUT.PRINTLN ("------Construct a------");
}
public void display () {
System.out.println (a);
}
}
public class B extends A {
int b;
public B (int b) {
Super (b);
SYSTEM.OUT.PRINTLN ("------construct b------");
}
}
public class C extends B {
int C;
public C (int c) {
Super (c);
SYSTEM.OUT.PRINTLN ("------construct c------");
}
public static void Main (string[] args) {
New C (9). display ();
}
}
The second way to do this is by combining it, by creating an object of an existing class in the new class, which is common, and the code is as follows
public class A {
int A;
public A (int a) {
This.a=a;
SYSTEM.OUT.PRINTLN ("------Construct a------");
}
public int Geta () {
return A;
}
}
public class b{
private int B;
Private a A=new a (2);
public B (int b) {
This.b=b;
System.out.println ("------constructor b------");
}
public void Show () {
B=b+a.geta ();
SYSTEM.OUT.PRINTLN ("------total:" +b);
}
public static void Main (string[] args) {
New B (2). Show ();
}
}
The third approach is the proxy, which encapsulates the detailed implementation of the class, providing only a subset of the methods of the class, the code is as follows
public class A {
Public A () {
SYSTEM.OUT.PRINTLN ("------Construct a------");
}
public void Method01 () {
SYSTEM.OUT.PRINTLN ("------method01------");
}
public void method02 () {
SYSTEM.OUT.PRINTLN ("------method02------");
}
public void Method03 () {
SYSTEM.OUT.PRINTLN ("------method03------");
}
}
public class b{
Private a a=new a ();
Public B () {
System.out.println ("------constructor b------");
}
public void Method01 () {
A.METHOD01 ();
}
}
Summary: Inheritance is achieved through the keyword extends, in the inheritance process, through inheritance, subclasses can get all the properties and methods of the parent class, the combination is to introduce another object's reference to the new class, in the new class can be directly used to introduce the common method of the class; proxies and combinations are very similar, but they don't mean the same thing. Combining the introduction of new classes is mainly to facilitate the use of some of the methods and properties of the introduction class, and the agent is mainly to hide some of the introduction of the class or property, through the proxy class to achieve this purpose.
Java inheritance, combinations, and proxies