1 //Abstract class Example:2 Abstract classShape13 {4 {5System.out.println ("Execute shape's initialization block ...");6 }7 PrivateString color;8 //defines an abstract method for calculating the perimeter,9 Public Abstract DoubleCalperimeter ();Ten //defines an abstract method that returns a shape. One Public AbstractString GetType (); A //defines the shape's constructor, which is not used to create a Shape object, but rather to create a subclass call - PublicShape1 () {} - PublicShape1 (String color) the { -System.out.println ("constructor to execute shape ..."); - This. color =color; - } + Public voidSetColor (String color) { This. color =color;} - PublicString GetColor () {returncolor;} + } A at classTriangleextendsShape1 - { - //defining the triangular sides of a triangle - Private DoubleA; - Private Doubleb; - Private DoubleC; in PublicTriangle (String color,DoubleADoubleBDoublec) - { to Super(color); + This. Setsides (a,b,c); - } the Public voidSetsides (DoubleADoubleBDoublec) * { $ if(A>b+c | | b>a+c | | c>a+b)Panax Notoginseng { -System.out.println ("The sum on both sides of the triangle must be greater than the third side"); the return; + } A This. A =A; the This. B =b; + This. C =C; - } $ //An abstract method that overrides the calculation perimeter of a shape class $ Public DoubleCalperimeter () - { - returna+b+C; the } - //overriding method of returning shapes for shape classesWuyi PublicString GetType () the { - returnTriangle; Wu } - } About $ Public classabstracttest - { - Public Static voidMain (string[] args) - { AShape1 S1 =NewTriangle ("Black", 3,4,5); + System.out.println (S1.gettype ()); the System.out.println (S1.calperimeter ()); - } $}
1 //The function of an abstract class; template action (in this case:2 //in the abstract parent class, the normal method of the parent class relies on an abstract method, and the abstract method is deferred to the subclass3 //to achieve)4 Abstract classSpeedmeter5 {6 Private Doubleturnrate;7 PublicSpeedmeter () {}8 Public Abstract DoubleGetradius ();9 Public voidSetturnrate (Doubleturnrate)Ten { One This. turnrate =turnrate; A } - //How to define calculation speed - Public Doublegetspeed () the { - //speed equals wheel radius *2*pi* rpm - returnJava.lang.Math.PI * 2 * getradius () *turnrate; - } + } - Public classCarspeedmeterextendsSpeedmeter + { A Public DoubleGetradius () at { - return0.28; - } - Public Static voidMain (string[] args) - { -Carspeedmeter CSM =NewCarspeedmeter (); inCsm.setturnrate (15); - System.out.println (Csm.getspeed ()); to } +}
Abstract classes and the role of abstract classes in Java