[关闭]
@Xc-liu 2018-09-01T00:48:18.000000Z 字数 2073 阅读 866

多个java类的组织方式

Java class


以构建极坐标系类为例具体说明下面几个问题。

同一个文件中包含主类(main class)在内的多个类

  1. //TestPloar.java
  2. public class TestPloar{
  3. public static void main(String[] args){
  4. Ploar fuck=new Ploar(4.0,Math.PI/4.0);
  5. Cartesian ha=new Cartesian(0,0);
  6. fuck.convert_to_Cartesian(ha);
  7. ha.display();
  8. }
  9. class Ploar{
  10. double r,theta;
  11. Ploar(double r0,double theta0){
  12. r=r0;theta=theta0;
  13. }
  14. void convert_to_Cartesian(Cartesian haha){
  15. haha.x=r*Math.cos(theta);
  16. haha.y=r*Math.sin(theta);
  17. }
  18. }
  19. class Cartesian{
  20. double x,y;
  21. Cartesian(double x0,double y0){
  22. x0=x;y=y0;
  23. }
  24. void display(){
  25. System.out.println("x:"+x+"y:"+y);
  26. }
  27. }
  28. }

上述代码在编译过程中出现如下报错:
此处输入图片的描述
原因在于java禁止在静态方法中引用非静态变量
具体地:main是静态方法,但是它里面实例化(建立引用)的是非静态类。
于是正确的写法为:

  1. //TestPloar.java
  2. public class TestPloar{
  3. public static void main(String[] args){
  4. Ploar fuck=new Ploar(4.0,Math.PI/4.0);
  5. Cartesian ha=new Cartesian(0,0);
  6. fuck.convert_to_Cartesian(ha);
  7. ha.display();
  8. }
  9. static class Ploar{//声明为静态类
  10. double r,theta;
  11. Ploar(double r0,double theta0){
  12. r=r0;theta=theta0;
  13. }
  14. void convert_to_Cartesian(Cartesian haha){
  15. haha.x=r*Math.cos(theta);
  16. haha.y=r*Math.sin(theta);
  17. }
  18. }
  19. static class Cartesian{//声明为静态类
  20. double x,y;
  21. Cartesian(double x0,double y0){
  22. x0=x;y=y0;
  23. }
  24. void display(){
  25. System.out.println("x:"+x+"y:"+y);
  26. }
  27. }
  28. }

所有内容写在同一个文件的一个主类中

  1. //Ploar0.java
  2. public class Ploar0{
  3. public static void main(String[] args){
  4. Ploar0 fuck=new Ploar0(4.0,Math.PI/4.0);
  5. fuck.convert_to_Cartesian();
  6. }
  7. double r,theta;
  8. Ploar0(double r0,double theta0){
  9. r=r0;theta=theta0;
  10. }
  11. void convert_to_Cartesian(){
  12. double x=r*Math.cos(theta);
  13. double y=r*Math.sin(theta);
  14. System.out.println("x:"+x+"y:"+y);
  15. }
  16. }

两个类分开写在两个文件中,只有一个含有mian方法

  1. //TestPloar1.java
  2. public class TestPloar1{
  3. public static void main(String[] args){
  4. Ploar1 fuck=new Ploar1(4.0,Math.PI/4.0);
  5. fuck.convert_to_Cartesian( );
  6. }
  7. }
  1. //Ploar1.java
  2. public class Ploar1{
  3. double r,theta;
  4. Ploar1(double r0,double theta0){
  5. r=r0;theta=theta0;
  6. }
  7. void convert_to_Cartesian(){
  8. double x=r*Math.cos(theta);
  9. double y=r*Math.sin(theta);
  10. System.out.println("x:"+x+"y:"+y);
  11. }
  12. }
  1. //makefile
  2. fuck:
  3. javac -cp /Users/liuxingchen/Desktop/ TestPloar1.java
  4. #编译不在同一目录下.java文件的方式
  5. fuck_run:
  6. cp /Users/liuxingchen/Desktop/Ploar1.class ./
  7. java TestPloar1
  8. #需要把编译生成的.class文件移到同一文件夹下,才能运行
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注