注意的知识点
1.静态方法不能调用实例方法。 改正:在实例方法前加static改为静态方法或者生成类的对象调用实例方法。 2.在继承中,方法的重写不能改变方法的类型和返回值,可以修改方法的参数表。 3.构造方法之间的调用使用关键字this。 4.this(1)要放在第一句,对于构造方法的调用要放在第一句。
class A{
A(int i){
}
A(){
System.out.println();
this(1);
}
}
public class Test {
public static void main(String[] args) {
A v1=new A(); 正确
B v2=new B(); 正确
B v3=new A(); 编译报错
A v4=new B(); 正确,自动转换
B v5=(B)v1; 编译正确,运行报错,类转换错误,因为v1本就不是B。
B v6=(B)v4; 正确,v4本就是B,只是披上了A的外衣。
}
}
class A{
}
class B extends A{
}
6.抽象类可以有方法体,但是不能创建实例对象。 7.接口中常量要进行初始化。接口中常量a(public static final可以省略)
要初始化。int a=123;
定义抽象类Shape(形状),包含形状名字属性及相应构造方法。 定义两个接口,一个接口IArea定义求面积的方法,一个接口IVolume定义求体积的方法。 定义Shape类的子类矩形(Rectangle)类,实现IArea接口。 定义长方体类同时实现IArea(求表面积)和IVolume接口。 在main方法中测试 考查知识点: 1.抽象类的定义。 2.接口的使用。 3.类方法的书写。
abstract class Shape
{
String name;
public Shape() {
this.name="几何形状";
}
}
class Rectangle extends Shape implements Iarea
{
int width,length;
double area;
public Rectangle() {}
public Rectangle(int width,int length) {
this.name="矩形";
this.width=width;
this.length=length;
}
@Override
public double Iarea() {
return width*length;
}
@Override
public String toString() {
String string="形状:"+this.name+"\t"+"长:"+this.length+"\t"+"宽:"+this.width+"\t"+"面积:"+this.Iarea();
return string;
}
}
class Cube extends Shape implements Ivolumn
{
int width,length,h;
double volumn;
public Cube() {}
public Cube(int width,int length,int h) {
// TODO Auto-generated constructor stub
this.name="长方体";
this.width=width;
this.length=length;
this.h=h;
}
@Override
public double Ivolumn() {
return width*length*h;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "形状:"+this.name+"\t"+"体积:"+this.Ivolumn();
}
}
public class Main{
public static void main(String[] args) {
Rectangle rt=new Rectangle(2,3);
System.out.println(rt.toString());
Cube cb=new Cube(3,2,1);
System.out.println(cb.toString());
}
}