Mees Van kaam Mees Van kaam - 1 year ago 75
Java Question

Creating objects in another class in java

I recently started working programming in Java for school and for a recent exercise i ran into some problems.

I currently have an object telephone, which can either be a mobile number, or a landline.
Now i want to make another class, containing contact details. In those contact details, there should be two Telephone objects: one mobile number (gsm), and one landline number(telephone). The sort of telephone number is declared in the class.

My question is how I should change the initialisation of the ContactDetails class, to accept the two new Telephone objects. And what it is exactly that I am doing wrong there.

thanks in advance!

public class Telephone {
private String sort;
public String number;

public Telephone(String sort, String number) {
this.sort = sort;
this.number = number;

public String getSort() {
return sort;

public String getNumber() {
return number;

public boolean isValidnumber(){
if(number.startsWith("0")) {
if (getSort() == "landline" && number.length() == 9) {
return true;
} else if (getSort() == "mobile" && number.length() == 10) {
return true;
} else return false;
else return false;

public class ContactDetails {
private String eMail;
Telephone telephone = new Telephone("landline", Telephone.number);
Telephone gsm = new Telephone("mobile", Telephone.number);

public ContactDetails(String eMail, Telephone telephone, Telephone gsm){
this.eMail = eMail;
this.telephone = telephone;
this.gsm = gsm;

Answer Source

You have two issues here:

  1. When initializing the Telephone gsm, you can't declare it as a Telefoon, as that class doesn't exist

  2. You have to initialize the Telephones with a number String. Telephone.number is referring to the number String of a Telephone object, which doesn't exist yet since you're just initializing the Telephone.

In order to make both of these work, change the 2 initializations of Telephone in ContactDetails to something like this:

Telephone telephone = new Telephone("landline", "5555555555");
Telephone gsm = new Telephone("mobile", "5555555555");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download