viernes, 11 de septiembre de 2020

Caso muy especifico de herencia y override en Java

Teniendo una estructura de herencia 


Donde

- Tenemos isBiped overriden en Kangaroo

- Kangaroo hereda el metodo getMarsupialDescription

Si implementamos la siguiente logica en el main de Kangaroo
 public class Marsupial {  
   public boolean isBiped() {  
     return false;  
   }  
   public void getMarsupialDescription() {  
     System.out.println("Marsupial walks on two legs: " + isBiped());  
   }  
 }  
 class Kangaroo extends Marsupial {  
   public boolean isBiped() {  
     return true;  
   }  
   public void getKangarooDescription() {  
     System.out.println("Kangaroo hops on two legs: " + isBiped());  
   }  
   public static void main(String[] args) {  
        Marsupial marsupialOne = new Marsupial();
        marsupialOne.getMarsupialDescription(); 
        marsupialOne.getKangarooDescription(); 

        // Marsupial Ref, Kangaroo obj        
        Marsupial marsupialTwo = new Kangaroo();
        marsupialTwo.getMarsupialDescription();
        marsupialTwo.getKangarooDescription(); 

        // Kangaroo Ref & obj
        Kangaroo kangaroo = new Kangaroo();
        kangaroo.getMarsupialDescription(); 
        kangaroo.getKangarooDescription(); 
   }  
 }  





Tenemos un output:
 
$ javac Marsupial.java
Marsupial.java:27: error: cannot find symbol
        marsupialOne.getKangarooDescription(); 
                    ^
  symbol:   method getKangarooDescription()
  location: variable marsupialOne of type Marsupial
Marsupial.java:32: error: cannot find symbol
        marsupialTwo.getKangarooDescription(); 
                    ^
  symbol:   method getKangarooDescription()
  location: variable marsupialTwo of type Marsupial
2 errors
Tratando de explicar este resultado debo primero lanzar una hipotesis de lo que esta haciendo la JVM

Al compilar

 
Marsupial marsupialOne = new Marsupial();
marsupialOne.getMarsupialDescription(); 
marsupialOne.getKangarooDescription();
Al ser marsupial una referencia tipo Marsupial, el compilador busca en esta clase la definicion de los metodos getMarsupialDescription y getKangarooDescription, y solamente encuentra el primero, el segundo no esta definido en esta clase por lo cual arroja el primer error

Para el caso:


 
Marsupial marsupialTwo = new Kangaroo();
marsupialTwo.getMarsupialDescription();
marsupialTwo.getKangarooDescription();
En este caso aunque el objeto es de tipo Kangaroo, la referencia en la que se almacena es de tipo Marsupial, el compilador, entonces, busca en esta clase la definicion de los metodos getMarsupialDescription y getKangarooDescription, y solamente encuentra el primero, el segundo no esta definido en esta clase por lo cual arroja el segundo error

En tiempo de compilacion aun no existe ningun objeto, asi que la JVM se limita a examinar la definicion de las clases


 
Kangaroo kangaroo = new Kangaroo();
kangaroo.getMarsupialDescription();
kangaroo.getKangarooDescription();
kangaroo es un objeto de tipo Kangaroo, la referencia en la que se almacena es de tipo Kangaroo, el compilador, entonces, busca en esta clase la definicion de los metodos getMarsupialDescription y getKangarooDescription, y solamente encuentra el segudno, el primero no esta definido en esta clase, entonces, busca en la clase padre, donde si encuentra la definicion y da por valida la sentencia

Se puede corregir los errores removiendo las lineas


 
marsupialOne.getKangarooDescription();
...
marsupialTwo.getKangarooDescription();
Output:
 
Marsupial walks on two legs: false
Marsupial walks on two legs: true
Marsupial walks on two legs: true
Kangaroo hops on two legs: true
Sabiendo que getMarsupialDescription llama al metodo isBiped, ¿porque hay resultados diferentes en marsupialOne y marsupialTwo? La respuesta es que marsupialOne es un objeto de tipo Marsupial y y marsupialTwo es un objeto Kagaroo, y estas clases tienen su propia implementacion del metodo isBiped, a la cual llaman respectivamente
Que ocurre si cambiamos la implementacion de isBiped a static en las dos classes
 
public static boolean isBiped()
 
Marsupial walks on two legs: false
Marsupial walks on two legs: false
Marsupial walks on two legs: false
Kangaroo hops on two legs: true 
En este caso, al ser isBiped un metodo estatico esta vinculado al tipo de referencia, no al objeto, asi, cuando se llama getMarsupialDescription usando una referencia Marsupial, se llama al metodo estatico isBiped de esa clase en particular

domingo, 21 de junio de 2015

Python, Modules

Empezamos una sesión interactiva en la consola, y revisaremos los nombres que tenemos definidos:















Problema: Tengo un módulo con una clase definida. Esta clase tiene un método










importo únicamente la clase, creo una instancia y uso el método








Cuando hago un cambio en la definición del método, espero que con volver a reimportar la clase, el cambio se vea reflejado. Pero no es asi, porque supuestamente la operación de import se lleva a cabo una sola vez. Asi que probamos importando el módulo entero(import script1)


domingo, 5 de abril de 2015

EventQueue.invokeLater

------------------------------------------------------------------------------------------------------------------
 Creating and modifying the components outside the EDT(Event Dispatching Thread) breaks the threading rules, but the breakage is not necessarily visible. The larger the program grows, the more likely it starts behaving badly sometimes, on some systems, and on some java versions

-------------------------------------------------------------------------------------------------------------------

- The complete Swing processing is done in a thread called EDT (Event Dispatching Thread). Therefore you would block the GUI if you would compute some long lasting calculations within this thread.

The way to go here is to process your calculation within a different thread, so your GUI stays responsive. At the end you want to update your GUI, which have to be done within the EDT. Now EventQueue.invokeLater comes into play. It posts an event (your Runnable) at the end of Swings event list and is processed after all other GUI events are processed.

Also the usage of EventQueue.invokeAndWait is possible here. The difference is, that your calculation thread blocks until your GUI is updated. This must not be used from the EDT.

Be careful not to update your Swing GUI from a different thread. In most cases this produces some strange updating/refreshing issues.

Still there is Java code out there that starts a JFrame simple from the main thread. This could cause issues, but is not prevented from Swing. Most modern IDEs now create something like this to start the GUI

---------------------------------------------------------------------------------------------------------------------

- You only need to use invokeLater when you want to update your UI from another thread that is not the UI thread (event dispatch thread).

Suppose you have a handler for a button-click and you want to change the text of a label when someone clicks the button. Then it's perfectly save to set the label text directly. This is possible because the handler for the button-click event runs in the UI thread.

Suppose, however, that on another button-click you start another thread that does some work and after this work is finished, you want to update the UI. Then you use invokeLater. This method ensures that your UI update is executed on the UI thread.

So in a lot of cases, you do not need invokeLater, you can simply do UI updates directly. If you're not sure, you can use isDispatchThread to check whether your current code is running inside the event dispatch thread.

--------------------------------------------------------------------------------------------------------------------
You need to do this only if you're not already on the event dispatch thread. Unless you've started new threads or executed code from the main thread all your code probably already runs from the event dispatch thread making this unnecessary. For example, all the UI event handlers are called on the event dispatch thread so you would not need to do that for code called from there.

--------------------------------------------------------------------------------------------------------------------

- Java's GUI is strictly single-threaded.
All GUI related things in java should always go through a single thread. The thread is our legendary "AWT-EventQueue-0"   . Hence all GUI related actions should necessarily go through the AWT Event thread. If not so you may end up in a deadlock. For small programs, this might never happen. But for a huge java application if you try frame.setVisible(true) kind of thing in main thread, you will soon find yourself searching a new job. What invokeLater() does is to post your Runnable in the AWT thread's event queue. So the code in your run method will be executed in the AWT-Eventqueue thread.

------------------------------------------------------------------------------------------------------------------

To avoid the possibility of deadlock, you must take extreme care that Swing components and models are created, modified, and queried only from the event-dispatching thread
-------------------------------------------------------------------------------------------------------------------
Most code that invokes Swing methods also runs on this thread. This is necessary because most Swing object methods are not "thread safe": invoking them from multiple threads risks thread interference or memory consistency errors. Some Swing component methods are labelled "thread safe" in the API specification; these can be safely invoked from any thread. All other Swing component methods must be invoked from the event dispatch thread. Programs that ignore this rule may function correctly most of the time, but are subject to unpredictable errors that are difficult to reproduce

-----------------------------------------------------------------------------------------------------------------

Tasks on the event dispatch thread must finish quickly; if they don't, unhandled events back up and the user interface becomes unresponsive.

----------------------------------------------------------------------------------------------------------------

When a Swing program needs to execute a long-running task, it usually uses one of the worker threads, also known as the background threads

--------------------------------------------------------------------------------------------------------------

SwingUtilities.invokeLater() vs EventQueue.invokeLater() 

-  SwingUtilities class was built to combine all general utility methods used in swing to be in one single class. Internally SwingUtilities.invokeLater() calls EventQueue.invokeLater()

sábado, 8 de noviembre de 2014

Instalando virtualenv para python2.7.8 y python3.4



http://toomuchdata.com/2014/02/16/how-to-install-python-on-centos/

domingo, 2 de noviembre de 2014

Instalar distintas versiones de python

- Instalar diferentes versiones de pyton
https://www.python.org/downloads/

- Descomprimir, entrar a cada carpeta de python
  • ./configure --prefix=/usr/local
  • make
  • make install
- Se tendrà esto en /usr/local
 lrwxrwxrwx. 1 root root       7 nov  2 15:01 python -> python2
lrwxrwxrwx. 1 root root       9 nov  2 15:01 python2 -> python2.7
-rwxr-xr-x. 1 root root 6221591 nov  2 14:59 python2.7
-rwxr-xr-x. 1 root root    1674 nov  2 15:01 python2.7-config
lrwxrwxrwx. 1 root root      16 nov  2 15:01 python2-config -> python2.7-config
lrwxrwxrwx. 1 root root       9 nov  2 15:21 python3 -> python3.4
-rwxr-xr-x. 2 root root 8777220 nov  2 15:19 python3.4
lrwxrwxrwx. 1 root root      17 nov  2 15:21 python3.4-config -> python3.4m-config
-rwxr-xr-x. 2 root root 8777220 nov  2 15:19 python3.4m
-rwxr-xr-x. 1 root root    3019 nov  2 15:21 python3.4m-config
lrwxrwxrwx. 1 root root      16 nov  2 15:21 python3-config -> python3.4-config
lrwxrwxrwx. 1 root root      14 nov  2 15:01 python-config -> python2-config


- Revisando el PATH:
    echo $PATH:
/usr/lib64/qt-3.3/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/manuel/bin

- Al ingresar "python" en la consola, se abrirà por defecto la version 2.7
 [manuel@oracle bin]$ python
Python 2.7.8 (default, Nov  2 2014, 14:58:46)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>


- Esto se resuelve cambiando el orden de las carpetas en el PATH, de tal manera que quede como primera opcion del python del sistema(/usr/bin)
Editar el archivo /home/usuario/.bashrc

export PATH=/usr/lib64/qt-3.3/bin:/usr/bin:/usr/local/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/manuel/bin

Ubicaciones
/usr/local/bin
   easy_install (python del sistema)
   easy_install-2.7
   easy_install-3.4

Instalaciòn de python
/usr/local/lib


La version de pip es la
pip 1.5.6 from /usr/lib/python2.6/site-packages/pip-1.5.6-py2.6.egg (python 2.6)


Fuentes:
http://toomuchdata.com/2014/02/16/how-to-install-python-on-centos/

miércoles, 29 de octubre de 2014

Preparàndo el Buildout -- Python

Como no tengo easy_install procedo a instalarlo

  • Yum
    • yum install python-setuptools python-setuptools-devel

sábado, 4 de enero de 2014