java学习55天2020/8/29
一定义一个基类BaseClass,从它派生出类DerivedClass。BaseClass有成员函数fn1(),fn2(),DerivedClass也有成员函数fn1(),fn2()。在主函数中声明对象来调用fn1(),fn2(),观察运行结果
class BaseClass{ public void fn1() { System.out.println("Base.fn1"); } public void fn2() { System.out.println("Base.fn2"); } } public class DerivedClass extends BaseClass { public void fn1() { System.out.println("Derived.fn1"); } public void fn2() { System.out.println("Derived.fn2"); } public static void main(String[] args) { DerivedClass m=new DerivedClass(); m.fn1(); m.fn2(); BaseClass n=new BaseClass(); n.fn1(); n.fn2(); n=new DerivedClass(); n.fn1(); n.fn2(); } }
三维坐标向量类
设计一个描述三维坐标的向量类vector3D,成员如下:
数据成员:
- 三个坐标x,y,z,float类型,私有访问属性
公有函数成员:
-
三个参数均有默认值的构造函数,默认值为0,0,0;
-
完成输入输出,输出格式为(x, y, z);
-
完成加法+、减法-、数乘*运算;
在主函数中定义两个vector3D类对象v1,v2,均不带参数,之后输入数字1或2选择为v1输入赋值,还是为v1和v2输入赋值,对v1和v2进行加、减运算,对v1进行数乘运算,乘数由用户输入,最后输出三种运算结果。
import java.util.Scanner; public class Vector3D { private float x; private float y; private float z; public Vector3D() { this.x=0; this.y=0; this.z=0; } public Vector3D(float x, float y, float z) { this.x = x; this.y = y; this.z = z; } public void input() { Scanner in=new Scanner(System.in); x=in.nextFloat(); y=in.nextFloat(); z=in.nextFloat(); } public void display() { System.out.println("("+x+","+y+","+z+")"); } public Vector3D add(Vector3D v) { float a=x+v.x; float b=y+v.y; float c=z+v.z; Vector3D p=new Vector3D(a,b,c); return p; } public Vector3D sub(Vector3D v) { float a=x-v.x; float b=y-v.y; float c=z-v.z; Vector3D p=new Vector3D(a,b,c); return p; } public Vector3D mul(float n) { float a=x*n; float b=y*n; float c=z*n; Vector3D p=new Vector3D(a,b,c); return p; } public static void main(String[] args) { int n; Vector3D v1=new Vector3D(); Vector3D v2=new Vector3D(); Scanner in=new Scanner(System.in); System.out.println("1.为三维向量v1赋值并进行数乘运算"); System.out.println("2.为三维向量v1、v2赋值并进行加、减运算"); System.out.print("请输入你要进行的操作编号:"); n=in.nextInt(); if(n==1) { float t; Vector3D v; System.out.print("请输入v1的三维坐标:"); v1.input(); System.out.print("请输入乘数:"); t=in.nextFloat(); v=v1.mul(t); System.out.print("数乘结果为:"); v.display(); } if(n==2) { System.out.print("请输入v1的三维坐标:"); v1.input(); System.out.print("请输入v2的三维坐标:"); v2.input(); System.out.print("相加结果为:"); (v1.add(v2)).display(); System.out.print("相减结果为:"); (v1.sub(v2)).display(); } } }