作业一、Java类与对象
(写出主要的内容)
1、写出以下程序的输出结果
public class SomeClass{
public int x;
}
public class TestClass
{
private static void test(int a, SomeClass obj){
a = 20;
obj.x = 100;
}
public static void main(String[] args){
int y = 1;
SomeClass myObj = new SomeClass();
test(y, myObj);
System.out.println("y= " + y);
System.out.println("myObj.x = " + myObj.x);
}
}
Answer:
y=1
myObj.x=100
2、以下代码中,Rectangle定义了一个长方形的类,Cube从Rectangle派生,定义了一个长方体的类。
Cube的构造函数public Cube(int length, int width, int height)用于给类的属性赋值,请给出其具体实现代码;
Cube的public int getArea()用于计算其体积,请给出其具体实现代码。请保留函数中已经给出的部分,但删除其中的注释。
public class Rectangle
{
private int length;
private int width;
public Rectangle(int length, int width)
{
this.length = length;
this.width = width;
}
public int calArea()
{
return length * width;
}
}
public class Cube extends Rectangle
{
private int height;
public Cube(int length, int width, int height)
{
this.length=length;
this.width=width;
this.height=height;
}
public int getArea()
{
return this.length*this.width*this.height;//这一句也是,但是今天CSDN好像故障了,代码块无法使用
}
3、函数public static void main(String[] args)中的某些代码存在语法错误,请依次找出它们,并简要说明错误的原因。
abstract public class Graph
{
abstract public double calArea();
}
public class Circle extends Graph
{
private double radius;
public Circle(double r)
{
radius = r;
}
public double calArea()
{
return Math.PI * radius * radius;
}
public static void main(String[] args)
{
Graph g;
g = new Graph();
Circle c;
c = new Circle(10);
g = c;
c = g;
}
}
Answer:
错误1:抽象类不能够直接被实例化成对象,由最上边的函数可以看出,Graph是abstract(抽象)类的,但是在主函数中直接定义p为Graph类。
错误2:c不能直接等于g,因为c所在的Circle类由g所在的Graph类派生,父类转换成子类需要显示转换,应该更正成c=(Circle)g;
4、请简要说说关键字final的用法。
Answer:
Final意味着将原本的变量/方法定义为常量,只能在初始化时进行一次赋值操作,用final进行定义后,这个变量/方法就不可以在程序中进行修改。
参考答案:
1、
y= 1
myObj.x = 100
2、供参考
public Cube(int length, int width, int height)
{
super(length, width);
this.height = height;
}
public int getArea()
{
return super.getArea() * height;
}
3、
语句g = new Graph();错误,因为不能创建抽象类的对象;
语句c = g;错误,因为类型不匹配,或者说基类的对象不能直接赋值给派生类的对象。
4、
(1)可用于修饰变量,这样的变量称为常量,只能赋值一次;
(2)可以用于修饰函数,这样的函数不允许被重写或者说覆盖;
(3)可以用于修饰类,这样的类不允许被继承,即不能有派生类。