Doubt with constructor when creating a JFrame. Java

1

I have a question at the time of being able to use the methods from a class that inherits from JFrame, like this:

class MarcoLibre extends JFrame{

}

In the constructor, I can access the methods that inherit from JFrame (and their corresponding inheritances).

class MarcoLibre extends JFrame{

   public MarcoLibre(){
      setTitle("JAVA");  //funciona
   }
 }

However, if I do it outside of the constructor, it does not work. Why from the constructor yes that I can and from outside him no? How could it be done without being in the constructor?

class MarcoLibre extends JFrame{

 setTitle("JAVA");  //no funciona

}

Then I have my main class where I create a frame.

import javax.swing.*;

public class LibreDisposicion {

 public static void main(String[] args) {
    // TODO Auto-generated method stub

    MarcoLibre miMarco = new MarcoLibre();
    miMarco.setVisible(true);

   }

}
    
asked by Javi 13.07.2018 в 19:38
source

2 answers

2

What happens is that all sentences must go within a class method and not in the class itself.

class MarcoLibre extends JFrame{
    public void titulo(){
        setTitle("JAVA");
    }
}

You can access any of the methods of the JFrame class (Parent Class) in any of the methods of the MarcoLibre class (Daughter Class), not only from the constructor.

public class LibreDisposicion {

    public static void main(String[] args) {
        MarcoLibre miMarco = new MarcoLibre();
        miMarco.titulo();
        miMarco.setVisible(true);

    }

}
    
answered by 13.07.2018 / 20:01
source
2

This happens because setVisible is a method that belongs to the Class JFrame , to be able to use any function or property of an inherited class it is required of a object whatever it is invoked, in In this case the Constructor is responsible for creating that object that we require, we can also point to that object with the reserved word this that refers to the properties and methods of the class.

When is this object created?

When instantiating the class, the first thing that is executed is the constructor which creates the aforementioned object.

is your case the class instance would be MarcoLibre miMarco = new MarcoLibre();

the Syntax is as follows:

  

[data type] [instance name] = new [constructor]

    
answered by 13.07.2018 в 19:53