In Java there is a special type called inheritance (inheritance), through inheritance we can reuse code, make the code concise, easy to expand. For example: There is a class of sharp, this class implements some of the methods of sharp, now we want to write a circle class, we think about, Ah Circle belongs to the one of sharp, we can inherit sharp! Yes, this is the mystery of inheritance!
Take a look at the following code:
/** * @authorGavin * This is a class that describes the shape*/classSharp { Public DoubleArea () {return0; } /** or a large area of sharp*/ StaticSharp Getlarger (A,sharp b) {if(A.area () >B.area ())returnA; Else returnb; }}/** * * @authorGavin * This is a circle class that inherits Sharp*/classCircleextendssharp{Private Static Final DoublePI =Math.PI; Private DoubleRadius=0; Circle (intradius) { This. Radius =radius; } Public DoubleArea () {//This method overrides the same name method in the parent class sharp returnpi* This. radius* This. Radius; } //Note that circle inherits Sharp, so circle has the Getlarger method in Sharp}/** * * @authorGavin * This is a square class that inherits Sharp*/classSquareextendssharp{Private DoubleSide = 0; Square (Doubleside) { This. Side =side; } Public DoubleArea () {//This method overrides the same name method in the parent class sharp returnside*side; } //Note that square inherits sharp, so Square has the Getlarger method in sharp. Public Static voidMain (string[] args) {Sharp a=NewCircle (2);//a parent class can have more than one subclass, as sharp here has two children, namely circle and square. Here, the parent class sharp can accept objects of all its subclasses. Sharp b=NewSquare (2); Sharp larger= Sharp.getlarger (A, b);//The parent class, Sharp, does not consider the shape of its subclasses, it automatically invokes the method of the screwdriver class object, because the method is inherited. System.out.println ("area of the shape of the area is:" +Larger.area ()); } }
007 the inheritance in JAVA