2017-01-29 4 views
3

Mein Programm zeigt einen Fehler "kann das Symbol 'getThePixels' nicht auflösen (in Klasse Main). Der Code erstellt im Grunde eine Monitor Klasse, die ein Objekt der Klasse Resolution enthält. Ich versuche, Resolution Klassenmethode über Monitorobjekt zuzugreifen. Im Folgenden ist der Code:Warum funktioniert dieser Kompositionscode nicht?

Main:

public class Main { 
    Resolution resolution = new Resolution(10); 
    Monitor monitor = new Monitor(12,13,14,resolution); 
    monitor.getThePixels().pix(); 
} 

Monitor:

public class Monitor { 
    private int height; 
    private int width; 
    private int length; 
    Resolution thePixels; 

    public Monitor(int height, int width, int length, Resolution thePixels) { 
     this.height = height; 
     this.width = width; 
     this.length = length; 
     this.thePixels = thePixels; 
    } 

    public int getHeight() { 
     return height; 
    } 

    public int getWidth() { 
     return width; 
    } 

    public int getLength() { 
     return length; 
    } 

    public Resolution getThePixels() { 
     return thePixels; 
    } 
} 

Auflösung:

public class Resolution { 
    private int pixels; 

    public Resolution(int pixels) { 
     this.pixels = pixels; 
    } 

    public void pix() { 
     System.out.println("resolution is" + pixels); 
    } 
} 
+2

@JeroenHeier Es ist nicht Kumpel nicht kompiliert. Das ist was er gesagt hat. – CKing

Antwort

5

Sie sollten Ihre Hauptklasse wie das schreiben.

public class Main { 
    public static void main(String[] args) { 
     Resolution resolution = new Resolution(10); 
     Monitor monitor = new Monitor(12,13,14,resolution); 
     monitor.getThePixels().pix(); 
    } 
} 

Sie können nicht Methode für Objekt innerhalb des Körpers der Klasse aufrufen.

3

Der Anruf an getThePixels ist in Ordnung. Java erlaubt jedoch nicht das Aufrufen von Methoden in der Mitte einer Klasse. Diese Art von Aufrufen muss in einer Methode, einem Konstruktor, einem anonymen Block oder einer Zuweisung erfolgen.

Es scheint, dass Sie diese Zeile aus einem main Methode aufzurufen gemeint:

public class Main { 
    public static void main(String[] args) { // Here! 
     Resolution resolution = new Resolution(10); 
     Monitor monitor = new Monitor(12,13,14,resolution); 
     monitor.getThePixels().pix(); 
    } 
} 
2

Sie schrieb:

public class Main { 
    Resolution resolution = new Resolution(10); 
    Monitor monitor = new Monitor(12,13,14,resolution); 
    monitor.getThePixels().pix(); 
} 

dies werde nicht ausgeführt werden, weil Sie keine main Methode haben um sie auszuführen: ich meine:

public static void main(String args[]) 

, wenn Sie es mit main Methode umschreiben, es funktioniert:

public class Main { 
    public static void main(String args[]){ 
     Resolution resolution = new Resolution(10); 
     Monitor monitor = new Monitor(12,13,14,resolution); 
     monitor.getThePixels().pix(); 
    } 
} 
Verwandte Themen