De C++ a Java
Características generales
Lenguaje interpretado
Máquina virtual de Java (JVM) interpreta la representación intermedia
llamada Bytecode
& Multiplataforma
&Seguridad y fiabilidad
'Lentitud
Unas 20 veces más lento que C
Plataforma:
Archivos Archivos Windows
javac java
.java .class JVM Linux
Solaris
...
De C++ a Java
Principales características
Lenguaje OO puro
Todo está encapsulado en clases
No existe typedef, struct o union: Clases
Gestión de memoria
Objetos = Referencias
No existe manipulación explícita de punteros: ->, &, *
Recolector automático de basura
Siempre new / no existe delete
No herencia múltiple
Tipos primitivos independientes de la plataforma
Boolean, char, byte, short, int, long, float, double
De C++ a Java
Características generales
C++ Java
int oddCount = 0; int oddCount = 0;
for (int j=0; j<20; j++){ for (int j=0; j<20; j++){
if (A[j] % 2 == 1){ if (A[j] % 2 == 1){
oddCount++; oddCount++;
} }
} }
De C++ a Java
Variables y constantes
C++ Java
// Objetos // Objetos
Fish pez=Fish(); Fish pez=new Fish ();
Location *pos=new Location(6,6); Location pos=new Location(6,6);
delete pos; pos = null;
// Constantes //Constantes
const int MAX=1000; //...dentro de una clase
static final int MAX=1000
De C++ a Java
Métodos / Funciones
C++ Java
De C++ a Java
Clases
C++ Java
cFish.h
%ROOT%\mbs\objects\Fish.java
#include “location.h“
class Environment; package mbs.objects;
class Fish{ import java.awt.Color;
int myId; public class Fish{
public: private static int nextAvailID = 1;
Fish():myLoc(NULL),myId(0); protected Color myColor;
Fish(const Location &loc); private Location myLoc;
void mover (Environment env); int myId;
private:
static int nextAvailID = 1; public Fish(Location loc){
Location *myLoc; // Inicializacion }
protected: public void mover (Environment env){
Color myColor; // Movemos el pez }
} }
cFish.cpp
Uso de static
Math.PI, Math.tan(x)
Contenedor de constantes
Clase System
Uso de final
Atributos: No pueden ser modificados
Métodos: No pueden ser especializados
Constructores
Por defecto, uno sin parámetros (Ejecución automática)
Sobrecarga según el número de parámetros
super(<parámetros>)
C++ Java
De C++ a Java
Herencia y polimorfismo
Interface
Clases con todos los métodos virtual en C++
Herencia múltiple de interfaces
Class Derived extends Base implements Interf1, [...], InterfN
Abstract
Intermedio entre clase e interfaz
C++ Java
Polimorfismo
Sobrecarga
No hay sobrecarga de operadores
Existe sobrecarga basada en ámbito y signatura
Reescritura / sustitución
Siempre está permitida
final
De C++ a Java
Herencia y polimorfismo
Polimorfismo
Variables polimórficas
Base variable = new Derived ()
this
super
(Derived)variable
Downcasting
C++ Java
Genericidad
C++: template <class T> class List {...}
A partir de Java 1.5
De C++ a Java
El “programa principal”
C++ Java
fishsim.cpp SimpleMBSDemo1.java
int main(int argc, char* argv[]) { public class SimpleMBSDemo1{
// Iniciar ejecución private static final int DELAY = 500;
return 0; public static void main(String[] args){
} // Iniciar ejecución
System.exit(0);
}
}
De C++ a Java
Entrada/Salida
C++
#include <iostream>
// Salida
cout << “Por pantalla” << endln
// Entrada
char *s;
cin >> s;
Java
// Salida
System.out.printl(“Por pantalla”);
// Entrada
BufferedReader in =new BufferedReader(new InputStreamReader(System.in));
String s=in.readline();
De C++ a Java
Cadenas
Clase String
Sobrecarga del operador +
Método toString() en las clases
String string1,string2;
char caracter, caracter1, caracter2;
int posicion;
De C++ a Java
Excepciones
C++ Java
class Exception1{}; class Exception1 extends Exception {}
class X {
public: public class X {
void f() { throw Exception1(); } public void f() throws Exception1{
}; throw new Exception1(); }
};
int main() {
X x; public static void main(String[] args)
try { {
x.f(); X x;
} catch(Exception1&) { try {
cout << “Error" << endl; x.f();
} } catch(Exception1 e) {
finally{ ...} System.out.println(e);
} }
finally{ ...}
}
De C++ a Java
Contenedores
Arrays
int[] a=new int[20];
Método length
Comprobación de límites
Colecciones
C++: STL
Java: Colecciones
Paquete java.util
De C++ a Java
Otros...
Archivos JAR
Compresión de varios archivos en uno (.class + recursos)
Bibliotecas interesantes de Java
Java.lang
Funciones matemáticas: java.lang.Math
Hebras de ejecución
Reflexión: java.lang.reflect
Clases envolventes (Wrappers)
Integer, Double, Boolean, ...
Comparable -> int compareTo(Object o)
Cloneable -> clone()
Entrada / Salida: java.io
Eventos: java.util.EventListener
De C++ a Java
Otros...
De C++ a Java
Applets
Jerarquía
De C++ a Java
Applets
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Event;
public class Simple extends Applet {
StringBuffer buffer;
public void init() {
buffer = new StringBuffer();
addItem("initializing... ");
}
public void start() { void addItem(String newWord) {
addItem("starting... "); System.out.println(newWord);
} buffer.append(newWord);
public void stop() { repaint();
addItem("stopping... "); }
} public void paint(Graphics g) {
public void destroy() { g.drawRect(0, 0, size().width - 1,
addItem("unloading..."); size().height - 1);
} g.drawString(buffer.toString(), 5, 15);
}
public boolean mouseDown
(Event event, int x, int y) {
addItem("click!... ");
return true;
}
}
De C++ a Java
Swing
De C++ a Java
Swing: Componentes
De C++ a Java
Swing: Componentes
De C++ a Java
Swing: Componentes
De C++ a Java
Swing
Swing es un framework
“No nos llame, nosotros le llamaremos”
MVC
Basado en contenedores
Alto nivel
JFrame
JDialog
JApplet
JComponent
Primero componer ... luego presentar
Manejador de eventos
Fuentes de eventos
“Oyentes de eventos” (Listeners)
De C++ a Java
Swing
import javax.swing.*;
public class Clase extends JFrame{
Clase(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add the ubiquitous "Hello World" label.
JLabel label = new JLabel("Hello World");
Creación por herencia getContentPane().add(label);
//Display the window.
pack();
setVisible(true);
}
public static void main(String[] args) {
Clase clase=new Clase();
}
}
import javax.swing.*;
public class Clase {
public Jframe frame;
Clase(){
//Create and set up the window.
frame = new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Creación por uso //Add the ubiquitous "Hello World" label.
JLabel label = new JLabel("Hello World");
frame.getContentPane().add(label);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
De C++ a Java Clase clase=new Clase();
}
}
Swing
Componentes
Etiquetas
...
JLabel label = new JLabel("Hello World");
frame.getContentPane().add(label);
Botones
...
JButton button = new JButton("I'm a Swing button!");
button.setMnemonic('i');
button.addActionListener(/*...create an action listener...*/);
frame.getContentPane().add(linea);
Barras de edición
...
public JTextField linea;
...
linea = new JTextField(2);
frame.getContentPane().add(linea);
De C++ a Java
Swing
De C++ a Java
Swing
Añadir un menú
...
JMenuBar menuBar;
JMenu menu, submenu;
JMenuItem menuItem;
...
// En el constructor...
menuBar = new JMenuBar();
menu = new JMenu("Acciones");
menuBar.add(menu);
menuItem = new JMenuItem("Convertir", KeyEvent.VK_C);
menu.add(menuItem);
converterFrame.setJMenuBar(menuBar);
De C++ a Java
Swing
Eventos
public class Clase implements ActionListener {
public Class(){
...
menuItem = new JMenuItem("Convertir", KeyEvent.VK_C);
menuItem.addActionListener(this);
convertTemp = new JButton("Convertir");
convertTemp.addActionListener(this);
...
}
public void actionPerformed(ActionEvent e) {
int tempFahr = (int)((Double.parseDouble(tempCelsius.getText()))* 1.8 + 32);
fahrenheitLabel.setText(tempFahr + " Fahrenheit");
}
}
CLICK!!
De C++ a Java
Referencias
De C++ a Java
http://www.lsi.upc.edu/~acastan/Docencia/Java.pdf
http://triton.towson.edu/~mzimand/os/Lect2-java-tutorial.html
http://www.cs.wustl.edu/~levine/courses/cs342/c++/javaVcpp-index.html
Bruce Eckel, Thinking in Java, 3rd Edition.
http://www.mindview.net/Books/TIJ/
Agustín Froufe, Java : Manual de Usuario y Tutorial. Rama 2002.
http://www.itapizaco.edu.mx/paginas/JavaTut/froufe/index.html
Aprenda Informática como si estuviera en primero
http://mec21.etsii.upm.es/ayudainf/
Java Technology: http://java.sun.com/
The Java Tutorial: http://java.sun.com/docs/books/tutorial
What’s new in Java 1.5:
http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html
De C++ a Java
Conclusions
De C++ a Java