构造方法
格式:public 类名(){}
特点:名称与类名相同;无返回值且构造方法名前不用void修饰;在创建对象 时构造方法自动调用并执行
作用:完成对类对类对象的初始化工作
利用构造方法来初始化圆柱类Cylinder的成员变量
class Cylinder{
private double radius ;
private int height;
private double pi=3.14;
public Cylinder(double r,int h){
radius=r;
height=h;
}
double area(){
return pi*radius*radius;
}
double volume(){
return area()*height;
}
}
public class Cwy{
public static vvoid main(String[] args){
Cylinder volu=new Cylinder(3.5,8);
System.out.println("圆柱体底面积:"+volu.area());
System.out.println("圆柱体体积:"+volu.volume());
}
}
继承
1.格式:public class 子类名 extrends 父类名{}
2.特点:子类可以继承父类所有非私有成员作为自己的成员,子类还可以有自己的内容
3.继承中变量访问的特点:先在子类局部范围找(即方法内部找);子类成员范围找;父类的成员范围找
4.java程序在执行子类的构造方法之前,会先调用父类中没有参数的构造方法,可利用super()语句来调用父类特定的构造方法
在子类Student中访问父类Person中的成员
class person{
protected String name ;
protected int age;
public Person() {}
public Person(String name;int age) {
this.name=name;
this.age=age;
}
protected void show() {
System.out.println("姓名:"+name+"年龄:"+age);
}
}
class Student extends Person{
private String department;
int age=20;
public Student(String xm,String dep) {
name=xm;
department =dep;
super.age=25;
System.out.println("子类Student中成员变量age="+age);
super.show();
System.out.println("系列:"+department);
}
}
public class Cwy {
public static void main(String[] args) {
Student stu=new Student("李小四","信息系");
}
}
抽象类
格式:abstract class 类名{
声明成员变量;
返回值的数据类型 方法名(参数表)
abstract 返回值的数据类型 方法名(参数表);
}
定义一个形状抽象类Shape,以该抽象类为父类派生出圆形子类Cricle和矩形子类Rectange
abstract class Shape{
protected String name;
public Shape (String xm){
name=xm;
System.out.println("名称:"+name);
}
abstract public double getArea();
abstract public double getLength();
}
class Cricle extends Shape{
private final double PI=3.14;
private double radius;
public Cricle(String shapeName,double r){
super(shapeName);
radius=r;
}
public double getArea(){
return PI*radius*radius;
}
public double getLength(){
feturn 2*PI*radius;
}
}
class Rectangle extrends Shape{
private double width;
private double height;
public Rectangle(String shapeName,double width,double height){
super(shapeName);
this.width=width;
this.height=height;
}
public double getArea() {
return width*height;
}
public double getLength(){
return 2*(width+height);
}
public class Cwy{
public static void main(String[] args){
Shape rect=new Rectangle("长方形:",6.5,8,9);
System.out.printl("面积:"+rect.getArea());
System.out.println(";周长="+rect.getLength);
}
}
}