关于调用类问题

副类有两种:1.副类对具体的值有定义;2.副类对具体的值没有定义,需要主类传值。

第一种:

  副类:

public class Plane extends GameObject {
    public void drawSelf(Graphics g) {
         g.drawImage(img, (int) x, (int) y, null);
    }

    public Plane(Image img, double x, double y) {
            this.img = img;
            this.x = x;
            this.y = y;
    }
}

  主类:

public class MyGameFrame extends JFrame {
    Image planeImage = GameUtil.getImage("images/飞机.png");
    Plane plane = new Plane(planeImage,250,250);

    @Override
    public void paint(Graphics g) {
     //g 就是连接两个类的点 plane.drawSelf(g);
//画飞机 } }

第二种:

副类:

public class Shell extends GameObject{

   double degree;      //角度
Image img = GameUtil.getImage("images/炮弹.png");

public Shell(){
        degree = Math.random()*Math.PI*2; // random()是0-1之间的随即数,2Π就是360度
        x = 200;
        y = 200;
        width = 10;
        height = 10;
        speed = 3;
    }

    public void drawSelf(Graphics g){
        //传进来一直画笔,作为连接两个类的点
        g.drawImage(img,(int)x,(int)y,width,height,null);
        //炮弹沿着任意角度飞行
        x += speed*Math.cos(degree);
        y += speed*Math.sin(degree);
    }

    public Shell(Image img){
        this.img = img;
    }
}

主类:

public class MyGameFrame extends JFrame {

Shell shell = new Shell(); //窗口绘制,自动被调用 不需要管他 ,g相当于一只画笔 @Override public void paint(Graphics g) {
     //g作为连接 shell.drawSelf(g); }

 

这两个的区别仅仅在于传值的问题。

 

posted @ 2021-12-05 13:27  _xiuxiu  阅读(57)  评论(0)    收藏  举报