@Xc-liu
2018-09-01T00:48:18.000000Z
字数 2073
阅读 884
Java
class
以构建极坐标系类为例具体说明下面几个问题。
//TestPloar.java
public class TestPloar{
public static void main(String[] args){
Ploar fuck=new Ploar(4.0,Math.PI/4.0);
Cartesian ha=new Cartesian(0,0);
fuck.convert_to_Cartesian(ha);
ha.display();
}
class Ploar{
double r,theta;
Ploar(double r0,double theta0){
r=r0;theta=theta0;
}
void convert_to_Cartesian(Cartesian haha){
haha.x=r*Math.cos(theta);
haha.y=r*Math.sin(theta);
}
}
class Cartesian{
double x,y;
Cartesian(double x0,double y0){
x0=x;y=y0;
}
void display(){
System.out.println("x:"+x+"y:"+y);
}
}
}
上述代码在编译过程中出现如下报错:
原因在于java禁止在静态方法中引用非静态变量
具体地:main是静态方法,但是它里面实例化(建立引用)的是非静态类。
于是正确的写法为:
//TestPloar.java
public class TestPloar{
public static void main(String[] args){
Ploar fuck=new Ploar(4.0,Math.PI/4.0);
Cartesian ha=new Cartesian(0,0);
fuck.convert_to_Cartesian(ha);
ha.display();
}
static class Ploar{//声明为静态类
double r,theta;
Ploar(double r0,double theta0){
r=r0;theta=theta0;
}
void convert_to_Cartesian(Cartesian haha){
haha.x=r*Math.cos(theta);
haha.y=r*Math.sin(theta);
}
}
static class Cartesian{//声明为静态类
double x,y;
Cartesian(double x0,double y0){
x0=x;y=y0;
}
void display(){
System.out.println("x:"+x+"y:"+y);
}
}
}
//Ploar0.java
public class Ploar0{
public static void main(String[] args){
Ploar0 fuck=new Ploar0(4.0,Math.PI/4.0);
fuck.convert_to_Cartesian();
}
double r,theta;
Ploar0(double r0,double theta0){
r=r0;theta=theta0;
}
void convert_to_Cartesian(){
double x=r*Math.cos(theta);
double y=r*Math.sin(theta);
System.out.println("x:"+x+"y:"+y);
}
}
//TestPloar1.java
public class TestPloar1{
public static void main(String[] args){
Ploar1 fuck=new Ploar1(4.0,Math.PI/4.0);
fuck.convert_to_Cartesian( );
}
}
//Ploar1.java
public class Ploar1{
double r,theta;
Ploar1(double r0,double theta0){
r=r0;theta=theta0;
}
void convert_to_Cartesian(){
double x=r*Math.cos(theta);
double y=r*Math.sin(theta);
System.out.println("x:"+x+"y:"+y);
}
}
//makefile
fuck:
javac -cp /Users/liuxingchen/Desktop/ TestPloar1.java
#编译不在同一目录下.java文件的方式
fuck_run:
cp /Users/liuxingchen/Desktop/Ploar1.class ./
java TestPloar1
#需要把编译生成的.class文件移到同一文件夹下,才能运行