Class introduction in javayugandhar vadlamudiA breaf notes on class,variable,method declaration.Accessing class variable and methods ,This keyword,Grabage Collection
Concepts of oopsSourabrata MukherjeeThis document provides an overview of object-oriented programming (OOP) concepts including class, object, encapsulation, inheritance, polymorphism, and software architectures like MVC. It discusses class design principles like single responsibility, open/closed, and dependency inversion. Common relationships between classes like association, aggregation, and composition are defined. Abstract classes and interfaces are compared. Use cases, class diagrams, and sequence diagrams are introduced in the context of software design.
Acyclic grapch directory 56(2)myrajendraAcyclic-graph directories use a graph structure without cycles to allow shared files and subdirectories that can be accessed by multiple users, which is useful for collaboration. They implement shared resources by either creating link entries that reference the shared file, ignoring the links to preserve the acyclic structure, or by duplicating file information in all sharing directories and ensuring consistency when modified.
Collections Api - JavaDrishti BhallaCore Java - Collections API - Methods of Traversing - Interfaces - MAP - SET - LIST - QUEUE and all its subtypes and methods.
Mocking in Java with MockitoRichard PaulMockito is a mocking framework for Java that allows developers to focus tests on interactions between objects rather than states. It provides test doubles like mocks and spies to simulate dependencies and verify expected interactions. Mockito allows mocking method calls and configuring return values or exceptions to test different scenarios. It provides default values for unstubbed calls to avoid overspecifying tests.
ThreadsMario Jorge PereiraEm Java, usamos a classe Thread do pacote java.lang para criarmos linhas de execução paralelas. A classe Thread recebe como argumento um objeto com o código que desejamos rodar.
Java Hibernate Programming with Architecture Diagram and Examplekamal kotechaJava Hibernate Introduction, Architecture and Example with step by step guidance to run the program especially for students and teachers.
Learn More @ http://java2all.com/technology/hibernate
Advanced Python : Static and Class Methods Bhanwar Singh MeenaThis presentation gives introduction to static and class methods in python with simple and easy to understand examples.
Design pattern (Abstract Factory & Singleton)paramisoftThis document discusses design patterns and provides examples of the Singleton and Abstract Factory patterns. It begins with an introduction to design patterns, their purpose and history. It then discusses the Singleton pattern in detail using a logger example and describes how to implement it using lazy instantiation. It also covers the Abstract Factory pattern using real world examples of a kitchen and chefs. It compares how these patterns would be implemented in code versus real objects.
El Proyecto de Reintroducción del Quebrantahuesos (Gypaetus barbatus) en Anda...Consejería de Sostenibilidad, Medio Ambiente y Economía AzulEl documento describe el proyecto de reintroducción del quebrantahuesos en Andalucía desde 1988 hasta la actualidad. El proyecto ha involucrado la cría en cautiverio, liberación e investigación de aves con el objetivo de restablecer una población viable de la especie en la región. A pesar de los desafíos como la mortalidad no natural, el proyecto ha logrado establecer 6 parejas reproductoras y 3 en formación, representando un avance significativo pero que aún requiere esfuerzos continuos.
Composite Design PatternFerdous Mahmud ShaonThe composite design pattern allows clients to treat both individual objects and compositions of objects uniformly. It composes objects into tree structures to represent part-whole hierarchies. The pattern allows clients to ignore the difference between compositions of objects and individual objects. This makes it possible to treat both kinds of objects uniformly.
Java ConstructorMujtabaNawaz4This document discusses various Java constructor concepts:
- Constructor overloading allows a class to have multiple constructors with different parameters. The compiler determines which to call based on the arguments.
- Constructor chaining calls one constructor from another using this() or super(). This allows constructing the object fully before the constructor body.
- The copy constructor initializes a new object with the values of an existing object of the same class. It copies each field to the new object. This allows cloning an object.
Construtores em JavaEderson LimaO documento discute construtores em orientação a objetos. Explica que um construtor é um método especial chamado quando um novo objeto é criado para alocar recursos e definir valores iniciais, e que construtores podem receber argumentos para inicializar informações ou obrigar o usuário a passar dados.
Inheritance In JavaDarpan ChelaniThis document discusses inheritance in Java. It defines inheritance as a mechanism where a subclass inherits the properties and behaviors of its parent class. It provides an example of single inheritance in Java where class B extends class A, inheriting its attributes and methods. The document also describes different types of inheritance like multilevel inheritance where a class inherits from another subclass, and hierarchical inheritance where a parent class has multiple subclasses. It provides an example of inheritance between different animal classes to demonstrate these concepts.
FDS (Sixth Edition) | C1 | Databases and Database UsersHarsh Verdhan RajThe document discusses databases and database management systems (DBMS). It provides an example of a UNIVERSITY database to illustrate how data is structured and related. Key advantages of the database approach include controlling redundancy, restricting unauthorized access, and enforcing integrity constraints. The history of database applications is reviewed, from early hierarchical and network systems to current technologies like XML, no-sql, and using databases on the web.
Paradigma de Programación Orientado a ObjetosAlberto BlumbergPOO: Origen, historia, características y conceptos utilizados en este difundido paradigma de programación.
Perl Programming - 01 Basic PerlDanairat ThanabodithammachariThe document discusses Perl programming and is divided into 5 modules: 1) Introduction to Perl, 2) Regular Expressions, 3) File Handling, 4) Connecting to Databases, and 5) Introduction to Perl Programming. It provides an overview of Perl variables, data types, operators, and basic programming structures. It also covers installing Perl, Perl modules, and interacting with files and databases.
How to write maintainable codePeter HiltonModern languages’ biggest problem isn’t having enough cool features, it’s unmaintainable code. The core of maintainable code is clean code with good tests, but that by itself is not enough. This talk introduces a range of techniques for writing and improving code for maintainability, including how to get better at naming, explaining code with tests, the few code comments you actually need, README-driven development and how to write Minimum Viable Documentation.
Attendees will see how to combine a number of techniques they have already encountered separately, plus at least one technique they’ve never heard of and can use immediately. Naming and abstraction are too hard to get right every single time, so you need to know when to add small doses of comments and documentation. More importantly, you need to know how to avoid wasting time on bad comments and unnecessary documentation without giving up entirely and not having any at all.
After the excitement of early adoption, and the joy of coding among experts comes the horror of your first maintenance project. As Jean-Paul Sartre said*, ‘Hell is other people’s code’. Whether you are a new Scala developer or an experienced team lead, your future developer experience and happiness depends on maintainable code.
Object-oriented Programming-with C#Doncho MinkovThe document discusses object-oriented programming concepts in C#, including defining classes, constructors, properties, static members, interfaces, inheritance, and polymorphism. It provides examples of defining a simple Cat class with fields, a constructor, properties, and methods. It also demonstrates using the Dog class by creating dog objects, setting their properties, and calling their bark method.
ABSTRACT CLASSES AND INTERFACES.pptJayanthiM15Abstract classes in Java can have both abstract and non-abstract methods. They cannot be instantiated and must be extended. Abstract methods do not have a method body. Interfaces in Java provide full abstraction and contain only abstract method declarations. Classes implement interfaces to inherit their methods. Both abstract classes and interfaces allow for abstraction and multiple inheritance in Java.
Interface in java ,multiple inheritance in java, interface implementationHoneyChintalmultiple inheritance in java, interface implementation, abstraction,
multiple inheritance in java using interface, how to use interface,
how to use java, how to execute a java code
Exception Handling In JavaparagThis document discusses exception handling in Java. It covers key concepts like exception classes, throwing and catching exceptions, creating custom exceptions, and best practices. Exception handling allows programs to gracefully deal with errors and exceptional conditions. The try-catch block is used to catch exceptions, and exceptions can be propagated or chained. Methods that throw exceptions must specify them using the throws clause. Finally blocks are used to perform cleanup code regardless of exceptions.
Design pattern (Abstract Factory & Singleton)paramisoftThis document discusses design patterns and provides examples of the Singleton and Abstract Factory patterns. It begins with an introduction to design patterns, their purpose and history. It then discusses the Singleton pattern in detail using a logger example and describes how to implement it using lazy instantiation. It also covers the Abstract Factory pattern using real world examples of a kitchen and chefs. It compares how these patterns would be implemented in code versus real objects.
El Proyecto de Reintroducción del Quebrantahuesos (Gypaetus barbatus) en Anda...Consejería de Sostenibilidad, Medio Ambiente y Economía AzulEl documento describe el proyecto de reintroducción del quebrantahuesos en Andalucía desde 1988 hasta la actualidad. El proyecto ha involucrado la cría en cautiverio, liberación e investigación de aves con el objetivo de restablecer una población viable de la especie en la región. A pesar de los desafíos como la mortalidad no natural, el proyecto ha logrado establecer 6 parejas reproductoras y 3 en formación, representando un avance significativo pero que aún requiere esfuerzos continuos.
Composite Design PatternFerdous Mahmud ShaonThe composite design pattern allows clients to treat both individual objects and compositions of objects uniformly. It composes objects into tree structures to represent part-whole hierarchies. The pattern allows clients to ignore the difference between compositions of objects and individual objects. This makes it possible to treat both kinds of objects uniformly.
Java ConstructorMujtabaNawaz4This document discusses various Java constructor concepts:
- Constructor overloading allows a class to have multiple constructors with different parameters. The compiler determines which to call based on the arguments.
- Constructor chaining calls one constructor from another using this() or super(). This allows constructing the object fully before the constructor body.
- The copy constructor initializes a new object with the values of an existing object of the same class. It copies each field to the new object. This allows cloning an object.
Construtores em JavaEderson LimaO documento discute construtores em orientação a objetos. Explica que um construtor é um método especial chamado quando um novo objeto é criado para alocar recursos e definir valores iniciais, e que construtores podem receber argumentos para inicializar informações ou obrigar o usuário a passar dados.
Inheritance In JavaDarpan ChelaniThis document discusses inheritance in Java. It defines inheritance as a mechanism where a subclass inherits the properties and behaviors of its parent class. It provides an example of single inheritance in Java where class B extends class A, inheriting its attributes and methods. The document also describes different types of inheritance like multilevel inheritance where a class inherits from another subclass, and hierarchical inheritance where a parent class has multiple subclasses. It provides an example of inheritance between different animal classes to demonstrate these concepts.
FDS (Sixth Edition) | C1 | Databases and Database UsersHarsh Verdhan RajThe document discusses databases and database management systems (DBMS). It provides an example of a UNIVERSITY database to illustrate how data is structured and related. Key advantages of the database approach include controlling redundancy, restricting unauthorized access, and enforcing integrity constraints. The history of database applications is reviewed, from early hierarchical and network systems to current technologies like XML, no-sql, and using databases on the web.
Paradigma de Programación Orientado a ObjetosAlberto BlumbergPOO: Origen, historia, características y conceptos utilizados en este difundido paradigma de programación.
Perl Programming - 01 Basic PerlDanairat ThanabodithammachariThe document discusses Perl programming and is divided into 5 modules: 1) Introduction to Perl, 2) Regular Expressions, 3) File Handling, 4) Connecting to Databases, and 5) Introduction to Perl Programming. It provides an overview of Perl variables, data types, operators, and basic programming structures. It also covers installing Perl, Perl modules, and interacting with files and databases.
How to write maintainable codePeter HiltonModern languages’ biggest problem isn’t having enough cool features, it’s unmaintainable code. The core of maintainable code is clean code with good tests, but that by itself is not enough. This talk introduces a range of techniques for writing and improving code for maintainability, including how to get better at naming, explaining code with tests, the few code comments you actually need, README-driven development and how to write Minimum Viable Documentation.
Attendees will see how to combine a number of techniques they have already encountered separately, plus at least one technique they’ve never heard of and can use immediately. Naming and abstraction are too hard to get right every single time, so you need to know when to add small doses of comments and documentation. More importantly, you need to know how to avoid wasting time on bad comments and unnecessary documentation without giving up entirely and not having any at all.
After the excitement of early adoption, and the joy of coding among experts comes the horror of your first maintenance project. As Jean-Paul Sartre said*, ‘Hell is other people’s code’. Whether you are a new Scala developer or an experienced team lead, your future developer experience and happiness depends on maintainable code.
Object-oriented Programming-with C#Doncho MinkovThe document discusses object-oriented programming concepts in C#, including defining classes, constructors, properties, static members, interfaces, inheritance, and polymorphism. It provides examples of defining a simple Cat class with fields, a constructor, properties, and methods. It also demonstrates using the Dog class by creating dog objects, setting their properties, and calling their bark method.
ABSTRACT CLASSES AND INTERFACES.pptJayanthiM15Abstract classes in Java can have both abstract and non-abstract methods. They cannot be instantiated and must be extended. Abstract methods do not have a method body. Interfaces in Java provide full abstraction and contain only abstract method declarations. Classes implement interfaces to inherit their methods. Both abstract classes and interfaces allow for abstraction and multiple inheritance in Java.
Interface in java ,multiple inheritance in java, interface implementationHoneyChintalmultiple inheritance in java, interface implementation, abstraction,
multiple inheritance in java using interface, how to use interface,
how to use java, how to execute a java code
Exception Handling In JavaparagThis document discusses exception handling in Java. It covers key concepts like exception classes, throwing and catching exceptions, creating custom exceptions, and best practices. Exception handling allows programs to gracefully deal with errors and exceptional conditions. The try-catch block is used to catch exceptions, and exceptions can be propagated or chained. Methods that throw exceptions must specify them using the throws clause. Finally blocks are used to perform cleanup code regardless of exceptions.
Java OCA teoria 4Valerio Radiceݺߣ quarta lezione al linguaggio Java 8 in preparazione alla certificazione OCA 1Z0-808.
Argomenti:
Design Pattern: Singleton
Classe Astratta
Interfaccia e interfaccia funzionale
Ereditarietà e costruttori
Super e this
Incapsulamento
Polimorfismo
Varargs
Overload e Override
Invocazione virtuale dei metodi
Lezione del 28-11-2017 tenuta da Valerio Radice presso Nextre Engeneering
https://www.nextre.it/corso/corso-java-oca/
Test Bank for Canadian Organizational Behaviour, 10th Edition, Steven McShane...izmarmelumTest Bank for Canadian Organizational Behaviour, 10th Edition, Steven McShane, Kevin Tasa
Test Bank for Canadian Organizational Behaviour, 10th Edition, Steven McShane, Kevin Tasa
Test Bank for Canadian Organizational Behaviour, 10th Edition, Steven McShane, Kevin Tasa
Presentazione della Dichiarazione di Dubai sulle OER alla comunità italiana -...Damiano Orru’Osservatorio sull’information literacy promuove un incontro online organizzato dalla rete Open Education Italia. n occasione della “Open Education Week 2025”, dal 3 al 7 marzo, la rete Open Education Italia organizza un incontro online dedicato alla presentazione della Dichiarazione di Dubai sulle Risorse Educative Aperte (OER) il 4 marzo 2025. https://www.aib.it/eventi/dichiarazione-dubai-oer-unesco/
Test Bank for Foundations of Financial Markets and Institutions, 4th Edition:...orrahnafTest Bank for Foundations of Financial Markets and Institutions, 4th Edition: Frank J. Fabozzi
Test Bank for Foundations of Financial Markets and Institutions, 4th Edition: Frank J. Fabozzi
Test Bank for Foundations of Financial Markets and Institutions, 4th Edition: Frank J. Fabozzi
New Methods of Literacy Research 1st Edition Peggy AlbersuxhcablendeNew Methods of Literacy Research 1st Edition Peggy Albers
New Methods of Literacy Research 1st Edition Peggy Albers
New Methods of Literacy Research 1st Edition Peggy Albers
Test Bank for Understanding Abnormal Behavior, 10th Edition : SuedementoggeTest Bank for Understanding Abnormal Behavior, 10th Edition : Sue
Test Bank for Understanding Abnormal Behavior, 10th Edition : Sue
Test Bank for Understanding Abnormal Behavior, 10th Edition : Sue
Test Bank for Systems Analysis and Design 8th Edition: KendallalawamajinaTest Bank for Systems Analysis and Design 8th Edition: Kendall
Test Bank for Systems Analysis and Design 8th Edition: Kendall
Test Bank for Systems Analysis and Design 8th Edition: Kendall
Learning Swift Building Apps for OSX, iOS, and Beyond Jon ManningjelieltoinksLearning Swift Building Apps for OSX, iOS, and Beyond Jon Manning
Learning Swift Building Apps for OSX, iOS, and Beyond Jon Manning
Learning Swift Building Apps for OSX, iOS, and Beyond Jon Manning
2 - Presentazione disturbo spettro autismo.pdfGiovanniBertoniݺߣ secondo gruppo "Pedagogia e Didattica Speciale della Disabilità Intellettiva (Cottini)"
Test Bank for Marketing Management, 3rd Edition, Greg Marshall, Mark JohnstonpplqadiriTest Bank for Marketing Management, 3rd Edition, Greg Marshall, Mark Johnston
Test Bank for Marketing Management, 3rd Edition, Greg Marshall, Mark Johnston
Test Bank for Marketing Management, 3rd Edition, Greg Marshall, Mark Johnston
Designing Intelligent Construction Projects Michael FrahmewoadetozitoDesigning Intelligent Construction Projects Michael Frahm
Designing Intelligent Construction Projects Michael Frahm
Designing Intelligent Construction Projects Michael Frahm
(eBook PDF) Auditing: A Practical Approach with Data Analytics by Raymond N. ...osanoarak(eBook PDF) Auditing: A Practical Approach with Data Analytics by Raymond N. Johnson
(eBook PDF) Auditing: A Practical Approach with Data Analytics by Raymond N. Johnson
(eBook PDF) Auditing: A Practical Approach with Data Analytics by Raymond N. Johnson
Essentials of Accounting for Governmental and Not for Profit Organizations 13...orakategyEssentials of Accounting for Governmental and Not for Profit Organizations 13th Edition Copley Test Bank
Essentials of Accounting for Governmental and Not for Profit Organizations 13th Edition Copley Test Bank
Essentials of Accounting for Governmental and Not for Profit Organizations 13th Edition Copley Test Bank
Essentials of Accounting for Governmental and Not-for-Profit Organizations 12...orakategyEssentials of Accounting for Governmental and Not-for-Profit Organizations 12th Edition Copley Test Bank
Essentials of Accounting for Governmental and Not-for-Profit Organizations 12th Edition Copley Test Bank
Essentials of Accounting for Governmental and Not-for-Profit Organizations 12th Edition Copley Test Bank
Digital Business Networks 1st Edition Dooley Solutions ManualidderkriboDigital Business Networks 1st Edition Dooley Solutions Manual
Digital Business Networks 1st Edition Dooley Solutions Manual
Digital Business Networks 1st Edition Dooley Solutions Manual
2. Ereditarietà e specializzazione Una delle caratteristiche distintive del paradigma di programmazione orientato agli oggetti è l'ereditarietà L'ereditarietà permette di definire nuove classi mediante l' aggiunta e/o la specializzazione di funzionalità ad altre classi già esistenti oppure appositamente progettate e definite Vedremo che questo meccanismo permette di: eliminare la duplicazione di codice (una classe che differisce di qualcosa rispetto ad un'altra può sfruttare l'ereditarietà e la specializzazione) introduce relazioni logiche tra classi
3. Ereditarietà - 1 Abbiamo già detto che ogni oggetto è riconducibile ad un’ entità astratta detta CLASSE . Tutti gli animali sono riconducibili alla classe Animale. Ogni animale reale è un esemplare della classe Animale. La classe descrive le proprietà e I comportamenti comuni a tutti gli esemplari della classe. Proprietà Nome Comportamento mangiare muoversi parlare (nel senso di emettere suoni)
4. Classe base Animale public class Animale { private String nome ; public Animale(String nomeProprio) { nome = nomeProprio; } public String getNome() { return nome ; } public void muoviti() { ……………………………… } public void mangia() { ……………………………… } public String parla() { return "???” //come parla un animale generico????; }} Come si muove, come mangia e come parla un animale generico? Costruttore : inizializza lo stato di un oggetto assegnando dei valori alle proprietà Metodo d’accesso : restituisce il nome dell’animale
5. Fido e Cocorito - 1 Animale Animale fido = new Animale(“Fido”); fido.muoviti(); fido.parla(); fido.mangia() fido.muoviti(); Animale coco = new Animale(“cocorito”); coco.muoviti(); coco.parla(); coco.mangia(); coco.muoviti(); Tra gli animali possiamo avere cani, pappagalli e altri con diverso comportamento Fido e Cocorito sono entrambi animali, e quindi possono mangiare, muoversi e parlare, ma non nello stesso modo. Come risolvere il problema?? dovrebbe fare baubau dovrebbe dire “ mi chiamo cooocorrito”
6. Fido e Cocorito - 2 Pappagallo Cane fido = new Cane(“Fido”); fido.muoviti(); fido.parla(); // baubau fido.mangia() fido.muoviti(); Animale coco = new Animale(“cocorito”); coco.muoviti(); coco.parla(); // mi chiamo cooocorrito coco.mangia(); coco.muoviti(); Posso creare due classi, una classe Cane e una classe Pappagallo Cane Per entrambe le classi definisco gli stessi attributi e gli stessi metodi
7. Sia Fido che Cocorito sono animali Essi hanno in comune attributi e metodi nome getNome() mangia() muoviti() parla() Sarebbe molto comodo disporre di un meccanismo che consenta di riutilizzare codice già scritto senza doverlo duplicare! Questo meccanismo è previsto dalla programmazione orientata agli oggetti ed è l’ ereditarietà Ereditarietà /2 Si tratta degli stessi attributi e metodi della classe Animale! Devo duplicarlo in Cane e in Papagallo??
8. Ereditarietà /3 Questo diagramma indica che Cane e Pappagallo derivano dalla classe Animale dalla quale ereditano attributi e metodi; in Java si dice che “estendono” la classe Animale Superclasse Classi derivate Cane Pappagallo Animale -nome +getNome() +muoviti() +mangia() +parla()
9. Classe specializzata Cane public class Pappagallo extends Animale { ……… .. public Pappagallo(String nome) { super (nome); } ………………… .. } nella definizione delle classi derivate scriviamo: public class Cane extends Animale { ……… .. public Cane(String nome) { super (nome); } ………………… .. } Viene usata la parola extends per derivare dalla classe base Animale Il costruttore richiama quello della classe base tramite la parola riservata super Stessa cosa per Pappagallo
10. Relazioni / Specializzazione Una classe si dice specializzazione di un'altra quando deriva da essa Cane o Pappagallo sono specializzazioni di Animale o classi derivate Animale è detta classe base o superclasse
11. Relazione “is a” Una relazione di ereditarietà è espressa dalla frase "E' un ...“ (is a) Ad esempio: Una giraffa è un animale. Un cane è un animale. Un aeroplano è un aeromobile; Un elicottero è un aeromobile. Animale è la superclasse o classe base; mentre giraffa e cane sono le sottoclassi o classi derivate. Aeromobile è la superclasse o classe base; mentre aeroplano e elicottero sono le sottoclassi o classi derivate.
12. Test 1: si tratta di ereditarietà? Fido è un cane . E’ una relazione di ereditarietà? Perché?
13. Risposta al test 1 No . Fido non eredita da cane ma è un'istanza di cane. Fido è un nome concreto e non astratto o generico, in altri termini Fido è un oggetto e non una classe. L'ereditarietà vale fra le classi. Per cui non c'è nessuna ereditarietà.
14. Test 2: si tratta di ereditarietà? Supponiamo di sviluppare un’applicazione per gestire un torneo di calcio. Esiste ereditarietà derivata da specializzazione tra le classi Squadra e Giocatore?
15. Risposta al test 2 No . Una Squadra è costituita da Giocatori, ma non possiamo dire né che un giocatore sia una squadra, né che la squadra sia un giocatore. Per esserci ereditarietà tra due classi devo poter dire che un’istanza della sottoclasse è anche istanza della superclasse, nel senso in cui dico che un’istanza di Gatto è anche istanza di Animale. Quella tra Squadra e Giocatore è una relazione di aggregazione (una squadra è costituita da giocatori)
16. Test 3 : si tratta di ereditarietà? In generale, tra due classi Padre e Figlio, esiste una relazione di ereditarietà ?
17. Risposta al test 3 No . Si può dire che Padre e Figlio estendano entrambi la classe Persona
18. L’ereditarietà nel mondo reale Per comprendere il concetto di ereditarietà possiamo ricorrere a molti esempi tratti dal mondo reale. Gli animali possono essere classificati in vertebrati e invertebrati; i vertebrati possono essere a loro volta classificati in mammiferi, rettili, pesci, uccelli, ecc... I mammiferi possono essere cani, gatti, uomini, balene e così via. Ognuna di tali tipologie di animali possiede alcune caratteristiche e funzionalità comuni (tutti gli animali si riproducono, si nutrono, si muovono, ...) e altre che sono strettamente proprie (ad esempio, solo i vertebrati hanno una struttura ossea, solo i mammiferi allattano i loro piccoli, soltanto l'uomo è in grado di parlare,...) .
19. L’ereditarietà nel mondo reale ciascuna classe eredita da quella superiore caratteristiche, funzioni e comportamenti ogni sottoclasse aggiunge caratteristiche e comportamenti specifici, non presenti nella classe superiore, oppure specializza secondo modalità proprie comportamenti presenti anche nella classe superiore specializzazione di comportamento : tutti gli animali si muovono, ma ognuno con modalità proprie nuovo comportamento : i mammiferi presentano il comportamento "Allattare la prole" non presente negli altri animali
20. Ereditarietà e polimorfismo/1 Torniamo ora al nostro esempio. Cane e Pappagallo ereditano tutti gli attributi e i metodi della classe base: nome, getNome(), parla(), muoviti(), mangia() C’è però un problema: Fido e Cocorito sono animali e quindi mangiano, si muovono e parlano, ma non allo stesso modo!!!! Fido quando parla fa “bau bau” Cocorito dice “ mi chiamo cooocorrito “ Anche il loro movimento è diverso e non mangiano lo stesso cibo Sarebbe utile avere un meccanismo che mi consenta di ridefinire I metodi, in modo da specializzarli per le due classi Questo meccanismo è il polimorfismo
21. Override public class Cane extends Animale { ……… .. public Cane(String nome) { super (nome); } public void parla() { System.out.println(“io faccio baubau”) ; } public void mangia() { System.out.println(“mangio le mie crocchette!!”) ;} } public void muoviti() { System.out.println(“mi muovo a quattro zampe!!”) ;} } } I metodi della classe base sono stati ridefiniti , anche se hanno conservato stesso nome e stessa definizione (parametri e restituzione) Questo tipo di polimorfismo è detto override Puoi fare qualcosa di analogo anche per la classe Pappagallo. Prova da solo!!
22. Ereditarietà / 4 Quando una classe estende una superclasse : ne eredita gli attributi e i metodi Inoltre può: definire nuovi attributi (per esempio per il cane possiamo aggiungere l’attributo razza ) definire nuovi metodi (per esempio per Cane possiamo definire il metodo corri() non presente nella superclasse ridefinire metodi già presenti nella superclasse (override di metodi)
23. Ereditarietà /5 Si parla di gerarchia di oggetti quando un oggetto possiede dei discendenti che a loro volta ne hanno altri (si pensi all'albero genealogico)
24. Polimorfismo /1 Permette di ridefinire il comportamento di un oggetto sia Fido che Cocorito hanno un metodo parla() ma il risultato è un pò diverso... perchè cambia l’implementazione dei due metodi (ovvero l’algoritmo relativo ai due metodi)
25. Polimorfismo / 2 Esistono più tipi di polimorfismo Overload – due o più metodi della stessa classe hanno lo stesso nome ma prendono argomenti diversi (lo abboamo già visto) Override – un metodo presente nella classe base viene ridefinito in una o più classi derivate (è legato all’ereditarietà) Polimorfismo dei riferimenti (anch’esso legato all’ereditarietà)
26. Riferimenti polimorfi/ 1 Il polimorfismo permette di manipolare le classi derivate con lo stesso puntatore o riferimento utilizzato per riferirsi alla classe base Cane bracco = new Cane ( "Braccobaldo" ); Animale fido = new Cane ( "Fido" ); System. out .println(fido.getNome()+ bracco.getNome()); Alla seconda linea viene creato un oggetto Cane che viene riferito con un puntatore di tipo Animale L'assegnazione è lecita perché Cane deriva da Animale Il contrario darebbe errore Riferimento Oggetto
27. Riferimenti polimorfi/2 Cosa succede se si vuole “convertire" un oggetto Animale generico in una classe derivata? Se l'assegnazione è lecita, ovvero l'oggetto generico è di tipo compatibile basta fare un casting esplicito Se l'assegnazione non è lecita viene generato un errore a runtime (non a compile time)
28. Riferimenti polimorfi/3 Animale fido = new Cane( "Fido" ); Animale silvestro = new Gatto( "Silvestro" ); // fido e silvestro sono entrambi animali, ma fido è un cane, mentre silvestro è un gatto Gatto g=silvestro; //ERRORE tempo di compilazione! //è errata perché silvestro è un riferimento di tipo animale: posso però convertirlo in riferimento di tipo gatto eseguendo il casting esplicito, nel seguente modo Gatto g = (Gatto) silvestro; // e' corretto perché l’istanza alla quale punta silvestro è di tipo gatto // la seguente genera errore run time perché fido e' un riferimento ad un oggetto di classe Cane Gatto g1 = (Gatto)fido;
29. Operatore instanceof E' possibile testare un oggetto per scoprire il suo tipo utilizzando l'operatore instanceof Animale fido = new Cane( "Fido" ); if (fido instanceof Gatto) { System. out .println( "Fido è un gatto" ); } else if (fido instanceof Cane) { System. out .println( "Fido è un cane" ); }
30. Classi e metodi astratte /1 All'inizio abbiamo definito la classe base Animale con il metodo parla() Questo metodo non ha nessuna utilità nella classe base: non è infatti possibile scrivere un qualsiasi algoritmo che produca un verso per la classe Animale. Che verso fa il generico animale? Forse parla() non è un metodo della classe base? Eppure tutti gli animali parlano, per cui è sicuramente un metodo della classe base. Allo stesso modo possiamo chiederci: tutti gli animali condividono il comportamento “muoversi”, ma come si muove un generico Animale? Salta? Striscia?
31. Classi e metodi astratti /2 Esiste un modo per dichiarare che una classe base ha metodi che sono comuni a tutte le classi che da essa derivano (muoversi, parlare, mangiare), ma questi metodi non possono essere implementati nella classe base: sono metodi astratti Saranno le classi derivate che dovranno implementare tutti questi metodi astratti nel modo corretto Una classe che presenta metodi astratti è detta classe astratta La classe astratta non può essere istanziata : è possibile immaginare un’esemplare di un generico animale? Noi riusciamo solo a immaginare un cane, un gatto, ….
32. Classi e metodi astratti /3 Si crea una classe con il metodo parla astratto public abstract class Animale { ………………… .. ………………… .. public abstract String parla(); //manca il corpo public abstract String muoviti(); //manca il corpo public abstract String mangia(); //manca il corpo ………………………… .. }
33. Classe Object /1 In Java tutte le classi hanno una classe base implicita Questa classe di chiama Object e contiene dei metodi utili alla Java Virtual Machine Scrivere public class Animale extends Object { ………………………… . } public class Animale { …………………… . } Equivale a scrivere
34. Classe Object /2 La classe Object e‘ la radice della gerarchia delle classi Java Tra i metodi contenuti in Object troviamo equals e toString public class Object { // Verifica se due oggetti sono uguali public boolean equals (Object obj) { } // Converte un oggetto in stringa public String toString () { } }
35. Ereditarietà singola e interfacce /1 In Java si può derivare da una sola classe Può essere necessario definire un nuovo oggetto con caratteristiche provenienti da due oggetti diversi Un pappagallo vola, un cane nuota Un'anatra può sia volare che nuotare Anche un aereo è un oggetto volante e una barca è un natante
36. Ereditarietà singola e interfacce /2 In java non è ammessa l'ereditarietà multipla; l'anatra non può estendere Animale, OggettiVolanti e OggettiNatanti Si utilizzano le interfacce (parola riservata interface ) Le interface sono simili alle classi astratte Esse hanno la dichiarazione dei metodi senza implementazione Possono avere solo metodi pubblic Non possono avere attributi Le classi derivate implementano le interfacce
37. Interfacce/1 Le nostre classi diventano public interface OggettiNatanti { public boolean nuota(); } public interface OggettiVolanti { public boolean vola(); }
38. Interfacce/2 public class Cane extends Animale implements OggettiNatanti { ... ... public boolean nuota() { return true ; } } public class Pappagallo extends Animale implements OggettiVolanti{ ... ... public boolean vola() { return true ; } }
39. Implementazione di interfacce public class Anatra extends Animale implements OggettiVolanti, OggettiNatanti{ ... ... public boolean nuota() { return true ; } public boolean vola() { return true ; } }
40. Esercizio 1.1 Scrivere la classe Pubblicazione avente come attributi: titolo editore Scrivere i costruttori, con e senza parametri e i metodi getter e setter Scrivere il metodo toString per restituire il valore degli attributi sotto forma di stringa Scrivere il metodo equals per verificare se l'oggetto corrente è uguale ad uno passato come argomento (è restituito un boolean) Scrivere la classe TestPubblicazione con il metodo main che crea due pubblicazioni con dati inseriti da tastiera, le visualizza e verifica se sono uguali
41. Esercizio 1.2 Definire una classe Rivista derivata da Pubblicazione con attributo specifico periodicità; ridefinire toString e equals Definire una classe Libro derivata da Pubblicazione con attributo specifico autore; ridefinire toString e equals Definire una classe TestPubblicazioni che crea alcune istanze di Rivista e di Libro con dati a scelta
42. Esercizio 2.1 Creare la gerarchia di classi: Punto (con attributi le coordinate x e y) Pixel (in più il colore) Punto3D (in più la coordinata z) Implementare le tre classi prevedendo per la classe Punto il metodo costruttore, i metodi set, get e i metodi toString e equals . Aggiungere nella classe Pixel e Punto3D i metodi per la gestione delle sottoclassi e ridefinire opportunamente i metodi toString e equals . Commentare le classi indicando quali metodi e quali attributi sono estesi, ereditati, ridefiniti.
43. Esercizio 2.2 Creare due istanze qualsiasi di Punto3D Visualizzare le coordinate dei due punti Verificare se i due punti coincidono e visualizzare opportuno messaggio