【问题标题】:Call Children's functions from parent从父级调用子级函数
【发布时间】:2013-03-19 15:04:42
【问题描述】:

我是 Java 新手,已经编写了一段时间的 C++ 和 OOP 以及对我来说是一次激动人心的新冒险。

我试图搜索这个问题,但我无法将答案转移到我的个人问题中,所以这里是:

Loop.java

public class Loop {
public int x;
public int y;
public int size;

public static void main(String [] args){
    new Loop(4, 4 ,2 );
}
private boolean game;

//---------------------------------------- constructor
public Loop(){
    }
public Loop(int height, int width, int cell_size){
    x = width;
    y = height;
    size = cell_size;
    System.out.println("Loop()");
    game = true;
    new Build_Cells(y,x);
    //run();
}
};

Build_Cells.java

import java.util.*;

public class Build_Cells extends Loop {
private List<List<Cell>> map = new ArrayList<List<Cell>>();
public int col;
public int rows;
public void printMap(){
    System.out.println("PrintMap()");
    for( int i = 0; i < map.size() /** col */; i++){
        for( int u = 0; u < map.get(i).size() /** rows */ ;u++){
            System.out.print(map.get(i).get(u).getState());
        }
        System.out.println();
    }
}
public Cell getCell(int a, int b){
    return map.get(a).get(b);
}
//---------------------------------------- constructor
public Build_Cells(){
}
public Build_Cells( int by, int bx){
    System.out.println("Build_Cells()");
    col = by;
    rows = bx;
    for( int i = 0; i < col ; i++){
        List<Cell> colObj = new ArrayList<Cell>(rows);
        map.add(y, colObj);
        for(int u = 0; u < rows; u++){
            colObj.add( new Cell() );
        }
    }
    printMap();
}
};

Cell.java

public class Cell extends Build_Cells {
private int state;
private int nemesis;
private int next;
private int getNem(int cs){
    int cata;
    if(cs == 1)
        cata = 0;
    else if(cs == (0 | 2 | 3) )
        cata = 1;
    else
        cata = 6;
    return cata;
}


//---------------------------------------- constructor
public Cell(){
    System.out.println("Cell()");
    set_state(5);
}
public void set_state(int input){
    state = input;
    nemesis = getNem(state);
}
public int getState(){
    return state;
}
};

如何使Build_CellsgetCell() 函数和CellgetState()setState() 函数可供Loop 使用?

【问题讨论】:

  • 你可能需要重新考虑你的班级层次结构
  • 您到底想在哪里调用这些?因为你实例化了 BuildCells。实例化后,您可以调用其方法。

标签: java function parent children


【解决方案1】:

您创建了Build_Cell 的实例,但没有存储对它的引用。如果你改变:

new Build_Cells(y,x);

Build_Cells buildCells = new Build_Cells(y,x);

您可以从Loop 致电buildCells.getCell()。您可以通过调用buildCells.getCell().getState() 获取单元格的状态或通过调用buildCells.getCell().setState() 设置其状态。

另外,Cell 可能不应该扩展 Build_Cells,因为它不使用它的任何功能。你可以阅读更多关于 Java 中 OOP 的内容here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-07
    • 2020-11-12
    • 1970-01-01
    • 2013-10-01
    • 1970-01-01
    相关资源
    最近更新 更多