Abstract classes in Java
Abstract class Planegraphics//Planar classes, abstraction classes
{
Private String shape; Shape
Construction method, with parameters
Public planegraphics (String shape)
{
This.shape=shape;
}
No parameters, construction methods
Public Planegraphics ()
{
This ("Unknown graph");
}
Abstract methods
public abstract double area ();
Non-abstract method, display area
public void print ()
{
System.out.println (this.shape+ "area:" +this.area ());
}
}
Rectangular class, inheriting plane class
Class Rectangle extends Planegraphics
{
protected double length; Long
protected double width; Wide
A method of constructing parameters
Public Rectangle (double length,double width)
{
This.length=length;
This.width=width;
}
Square Construction Method
Public Rectangle (double width)
{
Super ("Square");
This.width=width;
This.length=width;
}
Non-parametric construction method
Public Rectangle ()
{
}
Calculate the structure of a rectangle to implement the abstract method of the parent class
Public double Area ()
{
return width*length;
}
}
Design ellipse class, Inherit plane class
Class Eclipse extends Planegraphics
{
protected double radius_a; A-axis radius
protected double radius_b;
Construction method
Public Eclipse (double radius_a,double radius_b)
{
This.radius_a=radius_a;
This.radius_b=radius_b;
}
How to construct a circle
Public Eclipse (double radius_a)
{
Super ("Circle:");
This.radius_a=radius_a;
This.radius_b=radius_a;
}
Non-parametric construction method
Public Eclipse ()
{
}
Calculate the area of an ellipse
Public double Area ()
{
return math.pi*radius_a*radius_b;
}
}
public class Planegraphics_ex {
public static void Main (String[]args)
{
Planegraphics g=new Rectangle (10,20);
G.print ();
G=new Rectangle (10); Square
G.print ();
G=new Rectangle (); Unknown Graphics method
G.print ();
G=new Eclipse (10,20); Elliptic
G.print ();
G=new Eclipse (10); Round
G.print ();
G=new Eclipse (); Circular shape Unknown
G.print ();
}
}
1. The abstract class contains only the abstract method, the declaration of the method. and the concrete implementation of the method is implemented by its subclasses.
2. Abstract classes cannot be instantiated, and new objects cannot be created based on abstract classes.
3. Abstract classes can contain member variables and member methods, but abstract methods can only appear in abstract classes and cannot appear in other classes.
Abstract classes in Java