Hercles Posted September 7, 2014 at 01:23 PM Report Share #566479 Posted September 7, 2014 at 01:23 PM (edited) Caros, uma dúvida sobre a utilização de construtor. Ele é realmente necessário? Se tem o construtor padrão porque se cria um construtor diferente do padrão? class Cliente { String nome; String telefone; String endereco; public Cliente(String nome, String telefone, String endereco) { this.nome = nome; this.telefone = telefone; this.endereco = endereco; } } class Cliente { String nome; String telefone; String endereco; public Cliente() // este seria o padrão. } Edited September 7, 2014 at 01:24 PM by Hercles Link to comment Share on other sites More sharing options...
nelsonr Posted September 7, 2014 at 01:56 PM Report Share #566482 Posted September 7, 2014 at 01:56 PM Mostra um exemplo em como criavas um objecto usando cada uma dessas classes. Link to comment Share on other sites More sharing options...
Hercles Posted September 7, 2014 at 02:16 PM Author Report Share #566485 Posted September 7, 2014 at 02:16 PM (edited) Mostra um exemplo em como criavas um objecto usando cada uma dessas classes. public class TESTE { public static void main(String[] args) { Cliente c1 = new Cliente ("Fulano", "Rua A", "9999"); Cliente c2 = new Cliente ("Beltrano", "Rua B", "8888"); Pedido p1 = new Pedido(1, c1, 500, new GregorianCalendar()); PedidoExpresso p2 = new PedidoExpresso(2, c2, 500, new GregorianCalendar()); p2.setDataEntrega(new GregorianCalendar()); System.out.println(p1.toString()); System.out.println(p2.toString()); } } Edited September 7, 2014 at 02:18 PM by Hercles Link to comment Share on other sites More sharing options...
nelsonr Posted September 7, 2014 at 02:30 PM Report Share #566487 Posted September 7, 2014 at 02:30 PM Nesse exemplo apenas usas um dos construtores, o que tem os parametros. Ou seja, se a classe tivesse apenas o construtor padrao, sem parametros, não podias definir o objecto dessa forma Terias de instanciar o objecto sem parametros e depois atribuir os parametros de outra forma. Por essa razão, e para simplificar, uma classe permite construtores diferentes. 1 Report Link to comment Share on other sites More sharing options...
Hercles Posted September 7, 2014 at 02:35 PM Author Report Share #566488 Posted September 7, 2014 at 02:35 PM Pode se dizer que o Construtor Padrão teria que digitar valores para as variares no próprio construtor? No outro tipo não, o que facilitaria alguns "processos". Link to comment Share on other sites More sharing options...
shumy Posted September 8, 2014 at 08:18 PM Report Share #566581 Posted September 8, 2014 at 08:18 PM Outra razão adicional, é o facto de poderes forçar algumas pré-condições para utilizares apenas objectos que consideres válidos. É uma forma de forçar contratos, embora existam outras técnicas mais usualmente utilizadas, como o "Builder Pattern" Aqui há coisa de 2 anos fazia umas malhas de croché, depois fartei-me e fui para informática! Link to comment Share on other sites More sharing options...
Hercles Posted September 8, 2014 at 09:14 PM Author Report Share #566589 Posted September 8, 2014 at 09:14 PM Builder Pattern ?? vou pesquisa sobre... Link to comment Share on other sites More sharing options...
shumy Posted September 8, 2014 at 10:05 PM Report Share #566594 Posted September 8, 2014 at 10:05 PM Builder Pattern ?? vou pesquisa sobre... É utilizado por exemplo no JavaFX http://blog.netopyr.com/2012/01/24/advantages-of-javafx-builders/ 1 Report Aqui há coisa de 2 anos fazia umas malhas de croché, depois fartei-me e fui para informática! Link to comment Share on other sites More sharing options...
KTachyon Posted September 8, 2014 at 10:41 PM Report Share #566599 Posted September 8, 2014 at 10:41 PM (edited) Também podem ser decentemente utilizados com o Guice para fazer injecção de dependências. Mas no fundo, nem todos os objecto podem (ou devem) ser inicializados "peça a peça". Se queres um objecto num estado consistente logo no momento da inicialização, reforças a necessidade de inicialização colocando um construtor com os argumentos que irão receber os valores que permitem a inicialização do objecto. Isso faz com que o construtor padrão não seja criado (a não ser que o cries também). Edited September 8, 2014 at 10:41 PM by KTachyon “There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.” -- Tony Hoare Link to comment Share on other sites More sharing options...
Hercles Posted September 9, 2014 at 10:33 AM Author Report Share #566625 Posted September 9, 2014 at 10:33 AM (edited) O interessante que observei que ao criar um construtor se pode criar restrições... class Transporte extends Embarcacao { double potencia; double carga; public Transporte(int capacidade, double velocMax, double comprimento, double largura, double potencia, double carga) { super(capacidade, velocMax, comprimento, largura); if (potencia < carga) // restrição potencia = carga; this.potencia = potencia; this.carga = carga; } } Edited September 9, 2014 at 10:35 AM by Hercles Link to comment Share on other sites More sharing options...
Hercles Posted September 11, 2014 at 11:41 AM Author Report Share #566816 Posted September 11, 2014 at 11:41 AM (edited) Caros, sei que é uma pergunta boba, mas é que não sei rsrs... Quanto criei ai embaixo a classe cliente, logo abaixo o contrutor "public Cliente(String nome, String telefone, String endereco)" estas variáveis: nome, telefone e endereço são as mesmas da classe cliente? ou são outras que vão ser atribuintas a estas? Eu poderia criar outro nome para as variáveis do construtor? class Cliente { String nome; String telefone; String endereco; public Cliente(String nome, String telefone, String endereco) { this.nome = nome; this.telefone = telefone; this.endereco = endereco; } } Edited September 11, 2014 at 11:43 AM by Hercles Link to comment Share on other sites More sharing options...
HappyHippyHippo Posted September 11, 2014 at 12:24 PM Report Share #566818 Posted September 11, 2014 at 12:24 PM estas variáveis: nome, telefone e endereço são as mesmas da classe cliente? não Eu poderia criar outro nome para as variáveis do construtor? até podias chamar huguinho, zezinho e luizinho ... class Cliente { String nome; String telefone; String endereco; public Cliente(String huguinho, String zezinho , String luizinho) { this.nome = huguinho; this.telefone = zezinho; this.endereco = luizinho; } } IRC : sim, é algo que ainda existe >> #p@p Portugol Plus Link to comment Share on other sites More sharing options...
Hercles Posted September 11, 2014 at 02:55 PM Author Report Share #566832 Posted September 11, 2014 at 02:55 PM Entendi... Mas na hora de criar o objeto, vou chamar as " huguinho, zezinho e luizinho" , ok? Link to comment Share on other sites More sharing options...
HappyHippyHippo Posted September 11, 2014 at 03:21 PM Report Share #566834 Posted September 11, 2014 at 03:21 PM public class TESTE { public static void main(String[] args) { Cliente c1 = new Cliente ("Fulano", "Rua A", "9999"); // <--- onde está a confusão ??? // ... } } IRC : sim, é algo que ainda existe >> #p@p Portugol Plus Link to comment Share on other sites More sharing options...
Hercles Posted September 11, 2014 at 03:36 PM Author Report Share #566838 Posted September 11, 2014 at 03:36 PM (edited) public class TESTE { public static void main(String[] args) { Cliente c1 = new Cliente ("Fulano", "Rua A", "9999"); // <--- onde está a confusão ??? System.out.println(Cliente.nome) // <--- Cliente.huguinho ? } } Edited September 11, 2014 at 03:40 PM by Hercles Link to comment Share on other sites More sharing options...
HappyHippyHippo Posted September 11, 2014 at 04:25 PM Report Share #566845 Posted September 11, 2014 at 04:25 PM estas variáveis: nome, telefone e endereço são as mesmas da classe cliente? não estas variáveis: huguinho, zezinho e luizinho são as mesmas da classe cliente? não IRC : sim, é algo que ainda existe >> #p@p Portugol Plus Link to comment Share on other sites More sharing options...
Hercles Posted September 11, 2014 at 04:46 PM Author Report Share #566849 Posted September 11, 2014 at 04:46 PM 🙂 ok Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now