SlideShare una empresa de Scribd logo
1 de 19
Descargar para leer sin conexión
Java course - IAG0040




             More Java Basics
                and OOP


Anton Keks                            2011
Construction
 ●
     All objects are constructed using the new keyword
     –   MyClass fooBar = new MyClass();
 ●
     Object creation always executes a constructor
     –   Constructors may take parameters as any other
         methods
 ●   Default constructor (without parameters) exists if
     there are no other constructors defined
 ●   Constructor is a method without a return type (it
     returns the object's instance), the name of a
     constructor is the same as of the class.
Java course – IAG0040                                    Lecture 3
Anton Keks                                                 Slide 2
Destruction
 ●
     No need to destroy objects manually
 ●
     Garbage Collector (GC) does the job of destruction
     –   Executed in background when memory gets low
     –   Can actually be faster than explicit deallocation
     –   Can be invoked manually with System.gc();
 ●   An object is destroyed if there are no references left to
     it in the program, this almost eliminates memory leaks
 ●   Out of scope local variables are also candidates
 ●   finalize() method may be used instead of a destructor,
     however, its execution is not guaranteed
Java course – IAG0040                                    Lecture 3
Anton Keks                                                 Slide 3
Conditions
 ●
         if-else
     –   if (boolean-expression)   a boolean-expression
                                   should return a boolean
            statement              or Boolean value
         else
            statement
 ●
         switch
                                   an expression can return an
     –   switch (expression) {     int, short, char, byte, their
            case X:                respective wrapper classes
               statement           (which are unboxed) or an
               break;              enum type
            default:
               statement           a statement is a single Java
               break;              statement or multiple
         }                         statements in curly braces { }

Java course – IAG0040                                      Lecture 3
Anton Keks                                                   Slide 4
While loops
 ●
         while
     –   while (boolean-expression)
           statement
     –   Executes the statement while boolean-expression evaluates to true
 ●       do-while
     –   do
           statement
         while (boolean-expression);
     –   Same, but boolean-expression is evaluated after each iteration, not
         before



Java course – IAG0040                                                 Lecture 3
Anton Keks                                                              Slide 5
For loops
 ●
         for loop
     –   for(initialization; boolean-expression; step)
            statement
     –   Example: for(int i=0, j=1; i < 5; i++, j*=2) {}
 ●
         for each loop (arrays and Iterables)
     –   for(variable : iterable)
           statement
     –   for (int a : new int[] {1,2,3}) {}
     –   iterates over all elements of an iterable, executing the
         statement for each of its elements, assigning the element itself
         to the variable
Java course – IAG0040                                             Lecture 3
Anton Keks                                                          Slide 6
break and continue
 ●
         break and continue keywords can be used in any loop
     –   break interrupts the innermost loop
     –   continue skips to the next iteration of the innermost loop
 ●
         goto keyword is forbidden in Java, but break and
         continue can be used with labels
     –   outer: while(true) {
            inner: while(true) {
               break outer;
            }
         }
     –   Labels can be specified only right before a loop. Usage of break or
         continue with a label affects the labeled loop, not the innermost
         one.
Java course – IAG0040                                                 Lecture 3
Anton Keks                                                              Slide 7
Arrays
 ●
         Array is a special type of Object
     –   Arrays are actually arrays of references
     –   Elements are automatically initialized with zeros or nulls
     –   Automatic range checking is performed, always zero based
     ●   ArrayIndexOutOfBoundsException is thrown otherwise
     –   Special property is accessible: length
 ●       Definition: type followed by [ ]: byte[] a; String s[];
 ●       Creation using the new keyword: byte[]             a = new byte[12];
 ●       Access: byte b = a[0]; byte b2 = a[a.length – 1];
 ●       Static initialization: byte[] a = new byte[] {1,2,3};
 ●       Multidimensional: int[][] matrix = new int[3][3];
Java course – IAG0040                                                  Lecture 3
Anton Keks                                                               Slide 8
Strings
 ●       An immutable char array with additional features
 ●       Literals: “!” same as new String(new char[] {'!'})
 ●       Any object can be converted toString()
 ●       All primitive wrappers understand Strings: new Integer(“3”)
 ●       Equality is checked with equals() method
 ●       String pooling
     –    “ab” != new String(“ab”)
     –    “a1” == “a” + 1
 ●       StringBuilder is used behind the scenes for concatenation

Java course – IAG0040                                            Lecture 3
Anton Keks                                                         Slide 9
Classpath
 ●
     Classpath tells the JVM where to look for
     packages and classes
        –   java -cp or java -classpath
        –   $CLASSPATH environment variable
 ●   Works like $PATH environment variable
 ●   Every used class must be present on classpath
     during both compilation and runtime



Java course – IAG0040                            Lecture 3
Anton Keks                                        Slide 10
Classpath example
 ●
     Your class net.azib.Hello
 ●   Uses org.log4j.Logger and com.sun.World
 ●   In filesystem:
        –   ~/myclasses/net/azib/Hello.class
        –   ~/log4j/org/log4j/Logger.class
        –   ~/lib/sun.jar, which contains com/sun/World.class
 ●
     Should be run as following:            (separated with “;” on Windows)

        –   java -cp myclasses:log4j:lib/sun.jar net.azib.Hello
                             --- classpath ---

Java course – IAG0040                                            Lecture 3
Anton Keks                                                        Slide 11
Java API documentation



      Let's examine the API documentation a bit:
       http://java.sun.com/javase/6/docs/api/
  (http://java.azib.net -> Lirerature & Links -> API documentation)




Java course – IAG0040                                         Lecture 3
Anton Keks                                                     Slide 12
Javadoc comments
 ●
         Javadoc allows to document the code in place
     –   Helps with synchronization of code and documentation
 ●       Syntax: /** a javadoc comment */
     –   Documents the following source code element
     –   Tags: start with '@', have special meaning
     ●   Examples: @author, @version, @param
     ●   @deprecated – processed by the compiler to issue warnings
     –   Links: {@link java.lang.Object}, use '#' for fields or methods
     ●   {@link Object#equals(Object)}
 ●       javadoc program generates HTML documentation

Java course – IAG0040                                                Lecture 3
Anton Keks                                                            Slide 13
Varargs
●
        A way to pass unbounded number of parameters to methods
●
        Is merely a convenient syntax for passing arrays
●       void process(String ... a)
    –   In the method body, a can be used as an array of Strings
    –   There can be only one varargs-type parameter, and it should
        always be the last one
●       Caller can use two variants:
    –   process(new String[] {“a”, “b”}) - the old way
    –   process(“a”, “b”) - the varargs (new) way
●       System.out.printf() uses varargs
Java course – IAG0040                                              Lecture 3
Anton Keks                                                          Slide 14
Autoboxing
 ●
     Automatically wraps/unwraps primitive types into
     corresponding wrapper classes
 ●
     Boxing conversion, e.g. boolean -> Boolean, int ->
     Integer
 ●
     Unboxing conversion, e.g. Character -> char, etc
 ●   These values are cached: true, false, all bytes, chars
     from u0000 to u007F, ints and shorts from -128 to
     127
 ●   Examples:
     Integer n = 5;               // boxing
     char c = new Character('z'); // unboxing
Java course – IAG0040                                Lecture 3
Anton Keks                                            Slide 15
Extending classes
 ●
     Root class: java.lang.Object (used implicitly)
 ●   Unlike C++, only single inheritance is supported
 ●   class A {}        // extends Object
     class B extends A {}
     –   new B() instanceof A == true
     –   new B() instanceof Object == true
 ●   Access current class/instance with this keyword
 ●   Access base class with super keyword

Java course – IAG0040                           Lecture 3
Anton Keks                                       Slide 16
Extending classes
 ●       All methods are polymorphic (aka virtual in C++)
     –   final methods cannot be overridden
     –   super.method() calls the super implementation (optional)
 ●       Constructors always call super constructors
     –   if no constructors are defined, default one is assumed
     ●   class A { }                 // implies public A() {}
     –   default constructor is called implicitly if possible
     ●   class B extends A {
            public B(int i) { }           // super() is called
            public B(byte b) { super(); } // same here
         }

Java course – IAG0040                                             Lecture 3
Anton Keks                                                         Slide 17
Abstract classes
 ●   Defined with the abstract keyword
 ●   Not a concrete class, cannot be instantiated
 ●
     Can contain abstract methods without implementation
 ●   abstract class Animal {     // new Animal() is not allowed
        private String name;
        String getName() { return name; }
        abstract void makeSound();
     }
 ●   class Dog extends Animal {
        void makeSound() {
           System.out.println(“Woof!”);
        }
     }

Java course – IAG0040                                   Lecture 3
Anton Keks                                               Slide 18
Interfaces
 ●
     Substitute for Java's lack of multiple inheritance
        –   a class can implement many interfaces
 ●
     Interface are extreme abstract classes without
     implementation at all
        –   all methods are public and abstract by default
        –   can contain static final constants
        –   marker interfaces don't define any methods at all, eg Cloneable
 ●   public interface Eatable {
        Taste getTaste();
        void eat();
     }
 ●   public class Apple implements Eatable, Comparable
     { /* implementation */ }

Java course – IAG0040                                             Lecture 3
Anton Keks                                                         Slide 19

Más contenido relacionado

La actualidad más candente

Java Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingJava Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingAnton Keks
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)arvind pandey
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaSanjeev Tripathi
 
Core Java introduction | Basics | free course
Core Java introduction | Basics | free course Core Java introduction | Basics | free course
Core Java introduction | Basics | free course Kernel Training
 
Core Java Certification
Core Java CertificationCore Java Certification
Core Java CertificationVskills
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsMahika Tutorials
 
An Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and RuntimeAn Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and RuntimeOmar Bashir
 
New Features Of JDK 7
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7Deniz Oguz
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For SyntaxPravinYalameli
 
Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz SAurabh PRajapati
 
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Akshay Nagpurkar
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My HeartBui Kiet
 

La actualidad más candente (20)

Java Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingJava Course 13: JDBC & Logging
Java Course 13: JDBC & Logging
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
Core java
Core javaCore java
Core java
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
Core Java Tutorial
Core Java TutorialCore Java Tutorial
Core Java Tutorial
 
Core java
Core java Core java
Core java
 
Core Java introduction | Basics | free course
Core Java introduction | Basics | free course Core Java introduction | Basics | free course
Core Java introduction | Basics | free course
 
Core Java Certification
Core Java CertificationCore Java Certification
Core Java Certification
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika Tutorials
 
An Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and RuntimeAn Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and Runtime
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
New Features Of JDK 7
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7
 
Presentation to java
Presentation  to  javaPresentation  to  java
Presentation to java
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For Syntax
 
Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
Java features
Java featuresJava features
Java features
 
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My Heart
 

Destacado

Programming with Java: the Basics
Programming with Java: the BasicsProgramming with Java: the Basics
Programming with Java: the BasicsJussi Pohjolainen
 
Basics of java 2
Basics of java 2Basics of java 2
Basics of java 2Raghu nath
 
Introduction to basics of java
Introduction to basics of javaIntroduction to basics of java
Introduction to basics of javavinay arora
 
Java Programming for Designers
Java Programming for DesignersJava Programming for Designers
Java Programming for DesignersR. Sosa
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handlingpinkpreet_kaur
 
Core java Basics
Core java BasicsCore java Basics
Core java BasicsRAMU KOLLI
 
Core Java Basics
Core Java BasicsCore Java Basics
Core Java Basicsmhtspvtltd
 
Java basics part 1
Java basics part 1Java basics part 1
Java basics part 1Kevin Rowan
 
Basics of java programming language
Basics of java programming languageBasics of java programming language
Basics of java programming languagemasud33bd
 
02 java basics
02 java basics02 java basics
02 java basicsbsnl007
 

Destacado (20)

Java Basics
Java BasicsJava Basics
Java Basics
 
PALASH SL GUPTA
PALASH SL GUPTAPALASH SL GUPTA
PALASH SL GUPTA
 
Programming with Java: the Basics
Programming with Java: the BasicsProgramming with Java: the Basics
Programming with Java: the Basics
 
Java basics notes
Java basics notesJava basics notes
Java basics notes
 
Basics of java 2
Basics of java 2Basics of java 2
Basics of java 2
 
Introduction to basics of java
Introduction to basics of javaIntroduction to basics of java
Introduction to basics of java
 
Java basics
Java basicsJava basics
Java basics
 
Java Programming for Designers
Java Programming for DesignersJava Programming for Designers
Java Programming for Designers
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
 
2. Basics of Java
2. Basics of Java2. Basics of Java
2. Basics of Java
 
Java basics
Java basicsJava basics
Java basics
 
Core java Basics
Core java BasicsCore java Basics
Core java Basics
 
Java Basics
Java BasicsJava Basics
Java Basics
 
OOPs in Java
OOPs in JavaOOPs in Java
OOPs in Java
 
Core Java Basics
Core Java BasicsCore Java Basics
Core Java Basics
 
Java basics part 1
Java basics part 1Java basics part 1
Java basics part 1
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Ppt on java basics
Ppt on java basicsPpt on java basics
Ppt on java basics
 
Basics of java programming language
Basics of java programming languageBasics of java programming language
Basics of java programming language
 
02 java basics
02 java basics02 java basics
02 java basics
 

Similar a Java Course 3: OOP

Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyAnton Keks
 
Session 38 - Core Java (New Features) - Part 1
Session 38 - Core Java (New Features) - Part 1Session 38 - Core Java (New Features) - Part 1
Session 38 - Core Java (New Features) - Part 1PawanMM
 
First fare 2011 frc-java-introduction
First fare 2011 frc-java-introductionFirst fare 2011 frc-java-introduction
First fare 2011 frc-java-introductionOregon FIRST Robotics
 
U3 JAVA.pptx
U3 JAVA.pptxU3 JAVA.pptx
U3 JAVA.pptxmadan r
 
Java Course 9: Networking and Reflection
Java Course 9: Networking and ReflectionJava Course 9: Networking and Reflection
Java Course 9: Networking and ReflectionAnton Keks
 
JAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESJAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESNikunj Parekh
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in javaElizabeth alexander
 
Adv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfAdv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfKALAISELVI P
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsAnton Keks
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructorShivam Singhal
 
Objective-c for Java Developers
Objective-c for Java DevelopersObjective-c for Java Developers
Objective-c for Java DevelopersMuhammad Abdullah
 
Wait for your fortune without Blocking!
Wait for your fortune without Blocking!Wait for your fortune without Blocking!
Wait for your fortune without Blocking!Roman Elizarov
 
Basics java programing
Basics java programingBasics java programing
Basics java programingDarshan Gohel
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java conceptsChikugehlot
 
Learn To Code: Introduction to java
Learn To Code: Introduction to javaLearn To Code: Introduction to java
Learn To Code: Introduction to javaSadhanaParameswaran
 

Similar a Java Course 3: OOP (20)

Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
 
Session 38 - Core Java (New Features) - Part 1
Session 38 - Core Java (New Features) - Part 1Session 38 - Core Java (New Features) - Part 1
Session 38 - Core Java (New Features) - Part 1
 
First fare 2011 frc-java-introduction
First fare 2011 frc-java-introductionFirst fare 2011 frc-java-introduction
First fare 2011 frc-java-introduction
 
U3 JAVA.pptx
U3 JAVA.pptxU3 JAVA.pptx
U3 JAVA.pptx
 
Java Course 9: Networking and Reflection
Java Course 9: Networking and ReflectionJava Course 9: Networking and Reflection
Java Course 9: Networking and Reflection
 
JAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESJAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICES
 
Jist of Java
Jist of JavaJist of Java
Jist of Java
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
 
Adv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfAdv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdf
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
 
Introduction to JAVA
Introduction to JAVAIntroduction to JAVA
Introduction to JAVA
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructor
 
Objective-c for Java Developers
Objective-c for Java DevelopersObjective-c for Java Developers
Objective-c for Java Developers
 
Wait for your fortune without Blocking!
Wait for your fortune without Blocking!Wait for your fortune without Blocking!
Wait for your fortune without Blocking!
 
Jvm internals
Jvm internalsJvm internals
Jvm internals
 
core java
core javacore java
core java
 
Basics java programing
Basics java programingBasics java programing
Basics java programing
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java concepts
 
Learn To Code: Introduction to java
Learn To Code: Introduction to javaLearn To Code: Introduction to java
Learn To Code: Introduction to java
 

Más de Anton Keks

Being a professional software tester
Being a professional software testerBeing a professional software tester
Being a professional software testerAnton Keks
 
Java Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUIJava Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUIAnton Keks
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design PatternsAnton Keks
 
Choose a pattern for a problem
Choose a pattern for a problemChoose a pattern for a problem
Choose a pattern for a problemAnton Keks
 
Simple Pure Java
Simple Pure JavaSimple Pure Java
Simple Pure JavaAnton Keks
 
Database Refactoring
Database RefactoringDatabase Refactoring
Database RefactoringAnton Keks
 
Scrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineerScrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineerAnton Keks
 
Being a Professional Software Developer
Being a Professional Software DeveloperBeing a Professional Software Developer
Being a Professional Software DeveloperAnton Keks
 

Más de Anton Keks (8)

Being a professional software tester
Being a professional software testerBeing a professional software tester
Being a professional software tester
 
Java Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUIJava Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUI
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design Patterns
 
Choose a pattern for a problem
Choose a pattern for a problemChoose a pattern for a problem
Choose a pattern for a problem
 
Simple Pure Java
Simple Pure JavaSimple Pure Java
Simple Pure Java
 
Database Refactoring
Database RefactoringDatabase Refactoring
Database Refactoring
 
Scrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineerScrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineer
 
Being a Professional Software Developer
Being a Professional Software DeveloperBeing a Professional Software Developer
Being a Professional Software Developer
 

Último

Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 

Último (20)

Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 

Java Course 3: OOP

  • 1. Java course - IAG0040 More Java Basics and OOP Anton Keks 2011
  • 2. Construction ● All objects are constructed using the new keyword – MyClass fooBar = new MyClass(); ● Object creation always executes a constructor – Constructors may take parameters as any other methods ● Default constructor (without parameters) exists if there are no other constructors defined ● Constructor is a method without a return type (it returns the object's instance), the name of a constructor is the same as of the class. Java course – IAG0040 Lecture 3 Anton Keks Slide 2
  • 3. Destruction ● No need to destroy objects manually ● Garbage Collector (GC) does the job of destruction – Executed in background when memory gets low – Can actually be faster than explicit deallocation – Can be invoked manually with System.gc(); ● An object is destroyed if there are no references left to it in the program, this almost eliminates memory leaks ● Out of scope local variables are also candidates ● finalize() method may be used instead of a destructor, however, its execution is not guaranteed Java course – IAG0040 Lecture 3 Anton Keks Slide 3
  • 4. Conditions ● if-else – if (boolean-expression) a boolean-expression should return a boolean statement or Boolean value else statement ● switch an expression can return an – switch (expression) { int, short, char, byte, their case X: respective wrapper classes statement (which are unboxed) or an break; enum type default: statement a statement is a single Java break; statement or multiple } statements in curly braces { } Java course – IAG0040 Lecture 3 Anton Keks Slide 4
  • 5. While loops ● while – while (boolean-expression) statement – Executes the statement while boolean-expression evaluates to true ● do-while – do statement while (boolean-expression); – Same, but boolean-expression is evaluated after each iteration, not before Java course – IAG0040 Lecture 3 Anton Keks Slide 5
  • 6. For loops ● for loop – for(initialization; boolean-expression; step) statement – Example: for(int i=0, j=1; i < 5; i++, j*=2) {} ● for each loop (arrays and Iterables) – for(variable : iterable) statement – for (int a : new int[] {1,2,3}) {} – iterates over all elements of an iterable, executing the statement for each of its elements, assigning the element itself to the variable Java course – IAG0040 Lecture 3 Anton Keks Slide 6
  • 7. break and continue ● break and continue keywords can be used in any loop – break interrupts the innermost loop – continue skips to the next iteration of the innermost loop ● goto keyword is forbidden in Java, but break and continue can be used with labels – outer: while(true) { inner: while(true) { break outer; } } – Labels can be specified only right before a loop. Usage of break or continue with a label affects the labeled loop, not the innermost one. Java course – IAG0040 Lecture 3 Anton Keks Slide 7
  • 8. Arrays ● Array is a special type of Object – Arrays are actually arrays of references – Elements are automatically initialized with zeros or nulls – Automatic range checking is performed, always zero based ● ArrayIndexOutOfBoundsException is thrown otherwise – Special property is accessible: length ● Definition: type followed by [ ]: byte[] a; String s[]; ● Creation using the new keyword: byte[] a = new byte[12]; ● Access: byte b = a[0]; byte b2 = a[a.length – 1]; ● Static initialization: byte[] a = new byte[] {1,2,3}; ● Multidimensional: int[][] matrix = new int[3][3]; Java course – IAG0040 Lecture 3 Anton Keks Slide 8
  • 9. Strings ● An immutable char array with additional features ● Literals: “!” same as new String(new char[] {'!'}) ● Any object can be converted toString() ● All primitive wrappers understand Strings: new Integer(“3”) ● Equality is checked with equals() method ● String pooling – “ab” != new String(“ab”) – “a1” == “a” + 1 ● StringBuilder is used behind the scenes for concatenation Java course – IAG0040 Lecture 3 Anton Keks Slide 9
  • 10. Classpath ● Classpath tells the JVM where to look for packages and classes – java -cp or java -classpath – $CLASSPATH environment variable ● Works like $PATH environment variable ● Every used class must be present on classpath during both compilation and runtime Java course – IAG0040 Lecture 3 Anton Keks Slide 10
  • 11. Classpath example ● Your class net.azib.Hello ● Uses org.log4j.Logger and com.sun.World ● In filesystem: – ~/myclasses/net/azib/Hello.class – ~/log4j/org/log4j/Logger.class – ~/lib/sun.jar, which contains com/sun/World.class ● Should be run as following: (separated with “;” on Windows) – java -cp myclasses:log4j:lib/sun.jar net.azib.Hello --- classpath --- Java course – IAG0040 Lecture 3 Anton Keks Slide 11
  • 12. Java API documentation Let's examine the API documentation a bit: http://java.sun.com/javase/6/docs/api/ (http://java.azib.net -> Lirerature & Links -> API documentation) Java course – IAG0040 Lecture 3 Anton Keks Slide 12
  • 13. Javadoc comments ● Javadoc allows to document the code in place – Helps with synchronization of code and documentation ● Syntax: /** a javadoc comment */ – Documents the following source code element – Tags: start with '@', have special meaning ● Examples: @author, @version, @param ● @deprecated – processed by the compiler to issue warnings – Links: {@link java.lang.Object}, use '#' for fields or methods ● {@link Object#equals(Object)} ● javadoc program generates HTML documentation Java course – IAG0040 Lecture 3 Anton Keks Slide 13
  • 14. Varargs ● A way to pass unbounded number of parameters to methods ● Is merely a convenient syntax for passing arrays ● void process(String ... a) – In the method body, a can be used as an array of Strings – There can be only one varargs-type parameter, and it should always be the last one ● Caller can use two variants: – process(new String[] {“a”, “b”}) - the old way – process(“a”, “b”) - the varargs (new) way ● System.out.printf() uses varargs Java course – IAG0040 Lecture 3 Anton Keks Slide 14
  • 15. Autoboxing ● Automatically wraps/unwraps primitive types into corresponding wrapper classes ● Boxing conversion, e.g. boolean -> Boolean, int -> Integer ● Unboxing conversion, e.g. Character -> char, etc ● These values are cached: true, false, all bytes, chars from u0000 to u007F, ints and shorts from -128 to 127 ● Examples: Integer n = 5; // boxing char c = new Character('z'); // unboxing Java course – IAG0040 Lecture 3 Anton Keks Slide 15
  • 16. Extending classes ● Root class: java.lang.Object (used implicitly) ● Unlike C++, only single inheritance is supported ● class A {} // extends Object class B extends A {} – new B() instanceof A == true – new B() instanceof Object == true ● Access current class/instance with this keyword ● Access base class with super keyword Java course – IAG0040 Lecture 3 Anton Keks Slide 16
  • 17. Extending classes ● All methods are polymorphic (aka virtual in C++) – final methods cannot be overridden – super.method() calls the super implementation (optional) ● Constructors always call super constructors – if no constructors are defined, default one is assumed ● class A { } // implies public A() {} – default constructor is called implicitly if possible ● class B extends A { public B(int i) { } // super() is called public B(byte b) { super(); } // same here } Java course – IAG0040 Lecture 3 Anton Keks Slide 17
  • 18. Abstract classes ● Defined with the abstract keyword ● Not a concrete class, cannot be instantiated ● Can contain abstract methods without implementation ● abstract class Animal { // new Animal() is not allowed private String name; String getName() { return name; } abstract void makeSound(); } ● class Dog extends Animal { void makeSound() { System.out.println(“Woof!”); } } Java course – IAG0040 Lecture 3 Anton Keks Slide 18
  • 19. Interfaces ● Substitute for Java's lack of multiple inheritance – a class can implement many interfaces ● Interface are extreme abstract classes without implementation at all – all methods are public and abstract by default – can contain static final constants – marker interfaces don't define any methods at all, eg Cloneable ● public interface Eatable { Taste getTaste(); void eat(); } ● public class Apple implements Eatable, Comparable { /* implementation */ } Java course – IAG0040 Lecture 3 Anton Keks Slide 19