如何从另一个类添加值(java)

时间:2014-06-28 09:59:22

标签: java

我有两个课程:教授和主题

public class Profesor {

private int numbClassroom;


public Profesor(int numbClassroom) {
    this.numbClassroom = numbClassroom;
}


public int getNumbClassroom() {
    return numbClassroom;
}

public void setNumbClassroom(int numbClassroom) {
    this.numbClassroom = numbClassroom;
}

public String ToString(){
    return "Number of classroom: "+numbClassroom;
} }

第二节课是:

public class Subject{
String name;
Profesor lecturer = new Profesor();
Date yearOfStudy;


public void Dodeli(Profesor p){
 ??????
}}

我不知道如何将教授像讲师一样加入当前主题

3 个答案:

答案 0 :(得分:1)

喜欢这个?我没有看到任何问题。

public void Dodeli(Profesor p){
   lecturer = p;
}

答案 1 :(得分:0)

Profesor lecturer = new Profesor();

无需实例化讲师。只是宣布它。然后有getter / setter方法

然后你可以将教授分配给主题

Subject subj = new Subject("OOP");  //assuming you have corresponding constructor
subj.setLecturer(new Professor());  //or if you have existing prof object

答案 2 :(得分:0)

可能需要这样的东西:尝试封装你的代码

public class Professor {


    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
 }


    public class Subject{

    private String name;
    private Professor professor;
    private int numbClassroom;
    private Date yearOfStudy;

    public int getNumbClassroom() {
        return numbClassroom;
    }

    public void setNumbClassroom(int numbClassroom) {
        this.numbClassroom = numbClassroom;
    }



    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Professor getProfesor() {
        return professor;
    }

    public void setProfesor(Professor profesor) {
        this.professor = profesor;
    }
    public void Dodeli(){
        System.out.println("Pofessor  "+getProfesor().getName()+" is teaching "+getName()+" in Room NO :"+getNumbClassroom());

    }
}

public class TestImpl {
    public static void main(String arr[])
    {
        Subject subject = new Subject();
        Professor professor = new Professor();
        subject.setName("Biology");
        professor.setName("MR.X");
        subject.setNumbClassroom(1111);
        subject.setProfesor(professor);
        subject.Dodeli();



    }
}