Inherit with java

You can do the class inherit other like this: 

class NomeDaClasseASerCriada extends NomeDaClasseASerHerdada

We show an sample:

Class 1: Eletrodomestico

package tiexpert;

public class Eletrodomestico {
private boolean ligado;
private int voltagem;
private int consumo;
public Eletrodomestico(boolean ligado, int voltagem, int consumo) {
  this.ligado = ligado;
  this.voltagem = voltagem;
  this.consumo = consumo;
  }
// (...)
}
Class 2: TV
package tiexpert;

public class TV extends Eletrodomestico {
private int canal;
private int volume;
private int tamanho;
public TV(int voltagem, int consumo, int canal, int volume, int tamanho) {
  super(false, voltagem, consumo);
  this.canal = canal;
  this.volume = volume;
  this.tamanho = tamanho;
 }
 //(...)
}
Instance:
package tiexpert;

public class ExemploHeranca {
  public static void mostrarCaracteristicas(TV obj) {
   System.out.print("Esta TV tem as seguintes características:\n"
   + "Tamanho: " + obj.getTamanho() + "\"\n"
   + "Voltagem Atual: "+ obj.getVoltagem() + "V\n"
   + "Consumo/h: " + obj.getConsumo() + "W\n");
   if (obj.isLigado()) {
    System.out.println("Ligado: Sim\n"
   + "Canal: " + obj.getCanal() + "\n"
   + "Volume: " + obj.getVolume()+"\n");
   } else {
  System.out.println("Ligado: Não\n");
 }
}
public static void main(String args[]) {
  TV tv1 = new TV(110950021);
  TV tv2 = new TV(2201270029);
  tv2.setLigado(true);
  tv2.setCanal(3);
  tv2.setVolume(25);
  mostrarCaracteristicas(tv1);
  mostrarCaracteristicas(tv2);
 }
}
Let’s trainning !!
Font: http://www.tiexpert.net/programacao/java/heranca.php

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.