Java essentials
by l.cuvillon
Access Modifier
Has access?               Same Class             Same Package      Subclass another package             Universe
private                   yes
(package-                 yes                    yes
private)
protected                 yes                    yes               yes
public                    yes                    yes               yes                                  yes
● Class visibility: private (useless) or protected are both forbidden.
● An inner class can/should be private or protected.
C++: a class has no access modifier.
● Attribute and Method: default modifier is (package-private).
C++: default modifier is private.
● If constructor is private: direct object creation unavailable; available through a public static
method (see singleton class). If protected: object creation is only available inside the current
package, or outside the package through the definition of a subclass (super()).
Demo: _modifierAccess
Java Main                                                    Console Input-Output                                        Array (static size)
 p u b l i c c l a s s HelloWorld {                             Scanner sc =                                             create         type [] tab =
   p u b l i c s t a t i c v o i d main (                              new S c a n n e r ( System . i n ) ;
              String [ ] args ) {                                                                                                                   new type[length ];
      System . o u t . p r i n t l n ( " H e l l o ! " ) ;      String text = sc . nextLine ( ) ;
                                                                                                                                        double tab[]={1.2,2.3};
   }                                                            double value2 = sc . nextDouble ( ) ;
 }                                                              i n t v a l u e=                                         access         tab[ i ]
                                                                    I n t e g e r . valueOf ( sc . nextLine ( ) ) ;
                                                                                                                         length         tab. length
                                                                System . o u t . p r i n t l n                           comparison     Arrays . equals(tab1,tab2)
Package                                                                  ( " i n p u t : "+t e x t+" ␣ "+v a l u e ) ;
                                                                                                                                        tab. equals(tab2)
 p a c k a g e f o o . com . g r a p h i c s ;
 i m p o r t f o o . com . u t i l s . ∗ ;                   using static methods from the type wrapper                  copy from      type [] dest = Arrays.
                                                             Class : Integer, Boolean . . .
                                                                                                                         index i to j          copyOfRange(tab,i, j );
  public       c l a s s MyWindows {
                                                             Demo: _inputOutput
 ...                                                                                                                     enhanced       for (type it : tab)
● Java files are organized in directories or                                                                             iteration             System.out. println ( it );
packages. A package name matches the di-                     Math                                                        ● Array are object in Java
rectory path, where the files are located.                                                                               Demo: _array, _arrayObject
                                                             Math.pow(a, b)                   Math.PI
Exemple: MyWindows class above is lo-                                                                                    2D array       int [][] twoD = new int[4][];
                                                             Math.log(x)                      Math.log10(x)
cated in the directory ./foo/com/graphics/                                                                                              twoD[0] = new int[4];
                                                             Math.floor(x)                    Math.ceil(x)
Demo: _packages                                                                                                                         twoD[1] = new int[3];
                                                             Math.random()                    Math.sqrt(x)
                                                             double ∈ [0, 1[
Naming Convention
var                             variable, reference
method()                        methods
ObjectClass                     Object Class
●Name of a class starts with an upper case.
●The filename of a source file is the name
of the public class inside, if any. Many
class can be defined in one file, but only
one can be public.
Java essentials
by l.cuvillon
String Methods                                   Java Class                                                     Inheritance
create          String str ="text";               public         c l a s s Person {                              public         c l a s s Student
                                                                                                                                extends Person {
                str =new String("Geek");
                                                      p u b l i c S t r i n g name ;
length          str . length ()                       p r o t e c t e d i n t a g e =1; // d e f a u l t             p r i v a t e double grade ;
                                                                             // i n i t i a l i z a t i o n
comparison      str . equals( otherStr )
                                                                                                                     // c o n s t r u c t o r s
split           String [] pieces =                    // o v e r l o a d e d c o n s t r u c t o r s                 p u b l i c S t u d e n t ( S t r i n g name ,
                                                      p u b l i c P e r s o n ( S t r i n g name ) {                                                 i n t grade ) {
                       input . split (",");                       t h i s . name = name ;                                       // c a l l p a r e n t c o n s t r u c t o r :
conversion      int x =                               }                                                                         super ( initialName ) ;
                                                                                                                                s u p e r . age = 0 ;
                   Integer . parseInt ("12");         p u b l i c P e r s o n ( S t r i n g name ,                              t h i s . grade = grade ;
                str = Integer . toString (x );                                        i n t age ) {                  }
                                                                 // c a l l a b o v e c o n s t r u c t o r :
Strings are immutable objects in java (if                        t h i s ( name ) ;                                  // new methods
modified, a new String object is created):                       t h i s . age = age ;                               p u b l i c i n t getGrade () {
                                                      }                                                                         return grade ;
copy            str = str2;       //is safe                                                                          }
                                                      // methods
                                                      p u b l i c i n t getAge ( ) {                                 // o v e r r i d e n method
                                                                 r e t u r n age ;                                   @Override
                                                      }                                                              public String toString () {
                                                                                                                                return super . toString ()
                                                      public       String toString () {                                        +" : "+g r a d e ;
                                                                 r e t u r n name+" : "+a g e ;                      }
                                                      }                                                          }
                                                  }
                                                                                                                ●super is a reference to parent object:
                                                 ● A default constructor (no parameters) ex-                    to access parent attribute, constructor or
                                                 ists only if no constructor has been defined.                  method.
                                                 ● Overloading of constructors and methods                      ●super() is mandatory in subclass construc-
                                                 is allowed.                                                    tor to call parent constructor, if parent has
                                                 ● this is a reference to current object.                       no default constructor.
                                                 ● this () to call an overloaded constructor.                   ● @Override annotation asks the compiler to
                                                 Must be the first instruction in a construc-                   verify the method is indeed the overriding of
                                                 tor.                                                           a base method.
                                                 ●To create an object form a class:                             ● Multiple inheritance is not allowed.
                                                 Person me = new Person("Loic");                                 But successive single inheritance:
                                                 with me, a reference on the created object.                     class Student extends Person { }
                                                 ●For a second reference on same object:                         class Sophomore extends Students { }
                                                 Person shadow = me;                                            Demo: _classInheritance
                                                 Demo: _classConstructorAndRef,
                                                 _methodParameterPassing
Java essentials
by l.cuvillon
Object Class methods                            Abstract class                                               Interface
. toString ()        @Override, return a         abstract          c l a s s Animal {                         public interface Printable {
                                                                                                               i n t v e r s i o n=" 1 " ; // s t a t i c f i n a l
                     string representation
                                                     public sleep (){;
. equals(otherObj) @Override, true if                   System . o u t . p r i n t l n ( " s l e e p " ) ;        void    p r i n t ( ) ; // a b s t r a c t   public
                   identical object                  };                                                       }
.hashCode()          @Override, return hash          // a b s t r a c t method
                     number of the object            a b s t r a c t p u b l i c void speak ( ) ;             c l a s s Dog i m p l e m e n t s P r i n t a b l e {
                     (equals() objects must      }                                                              i n t num = P r i n t a b l e . v e r s i o n ;
                     return same hashcode)
                                                                                                                  @Override
. clone ()           return reference on a       c l a s s Dog e x t e n d s A n i m a l {                        public void p r i n t (){
                     cloned object                                                                                  System . o u t . p r i n t l n ( "Dog" ) ;
                     (Do not use. Write a            @Override                                                    }
                                                     p u b l i c void speak () {
                     copy constructor !)
                                                        System . o u t . p r i n t l n ( "Wouf ! " ) ;            p u b l i c void speak () {
. getClass ()        return Object Class             }                                                               System . o u t . p r i n t l n ( "Wouf ! " ) ;
                     (name)                      }                                                                }
                                                                                                              }
Object is the superclass of all java classes.   used to shared method without implemta-
                                                tion (abstract when implementation is spe-                   ● to share a behavior between classes that
Note :                                          cific to subclass) and/or with implementa-                   otherwise are not related
● If not overridden, equals () compares the     tion between some subclass.                                  ● to use an object without knowing its type
                                                ● abstract class cannot be instantiated.
objects reference (same as ==, i.e if it is                                                                  but knowing it implements an interface
the same object) and not the content of
                                                ● if one abstract method, the class is nec-                  Example:
the objects.
● If not overriden, toString () return a
                                                essarily abstract.                                           -void printer ( Printable obj)   method
String compose of object Class and              ● abstract method has no body.                               available for any class implementing the
                                                                                                             interface:
hashCode.                                       ● if the subclass do no implement all the
● clone () should not be used. It requires      abstract methods, the derived/sub class is                        Dog husky= new Dog();
implements Cloneable to avoid exception         also abstract.                                                     printer (husky);
CloneNotSupportedException.
                                                C++: No abstract keyword. Abstract if                        - see the Comparable interface in collections
Demo:_classEqualsToStringClone                  pure virtual method(=0;)
                                                Demo:_classAbstract
                                                                                                             interface : pure abstract class. All methods
                                                                                                             have to be implemented by the new class.
                                                                                                             ● interface attribute is static final public.
                                                                                                             ● interface method is abstract public.
                                                                                                             ● A class can have multiple interfaces :
                                                                                                             B extends A implements interface1 , interface2
                                                                                                             ● An interface can inherit from another in-
                                                                                                             terface :
                                                                                                             InterfaceB extends Interface A {
                                                                                                             Demo:_classInterface
                                                                                                             For java>1.8, “default” modifier can be
                                                                                                             used with an interface method to add a de-
                                                                                                             fault method implementation.
Java essentials
by l.cuvillon
Inner/nested Class                                             Anonymous Class                                                    Final
 p u b l i c c l a s s Form2D {                                 public        class      Fenetre                                  final type name          constant var/reference
    C o l o r c o l o r = C o l o r . BLUE ;                                               e x t e n d s JFrame {
    Po in t2D o r i g i n = new P o i n t 2 D ( ) ;                                                                               final method()           overriding forbidden
  // ( o r new i n Form2D c o n s t r u c t o r )                   // F e n e t r e C o n s t r u c t o r
                                                                                                                                  final class              inheritance forbidden
                                                                    Fenetre (){
     // I n n e r c l a s s                                           JButton b =                                                 ● Keyword final to prevent modification.
     c l a s s Po int 2D {                                                new J B u t t o n ( " O f f " ) ;                       ● Keyword final applies to attribute (must
         int x , y ;
                                                                                                                                  be initialized when the constructor ends),
                                                                         b . addActionListener (
                                                                                                                                  local variable, parameter, method and
         public String toString () {                                      new A c t i o n L i s t e n e r ( ) {
         r e t u r n " [ "+ x +" , "+ y +" : "                               // anonymous c l a s s f r o m                       class.
                               + c o l o r +" ] " ;                          // A c t i o n L i s t e n e r i n t e r f a c e :   ● For final variables, initialization can be
         }                                                                   public void                                          done later after declaration (blank final)
     }                                                                        actionPerformed ( Action e ){                       C++: const for variable. (const has many
 }                                                                              j t e x t . setText (" c l i c k e d " ) ;
                                                                                                                                  other use in C++)
                                                                              }
● use for encapsulation and concise coding,                               }                                                       C++11: final available for object and
if the inner class is only used inside the outer                         );                                                       method.
class.                                                                                                                            Demo:_modifierFinal
                                                                     }
(Exemple: a point2D inside a Form2D)                            }
                                                                                                                                  Static
Note: -A inner class has access to the mem-
                                                               without anonymous class:                                           static type attr         value is common to
bers of its enclosing class (Exemple: color).
                                                                public        class      Fenetre                                                           all objects of the class
   -On contrary to normal class, inner class                                               e x t e n d s JFrame {
                                                                                                                                  static method()          can be called without
can be private or protected. Good design
                                                                    // F e n e t r e C o n s t r u c t o r                                                 an object instantiation
choice.
                                                                    Fenetre (){
                                                                                                                                  static class             can be instantiated
   -If public, inner class can be instantiated                        JButton b =
                                                                          new J B u t t o n ( " O f f " ) ;                       (only for inner          without an instance of
from outside (bad design and the syntax be-
                                                                                                                                  class)                   the outer class
low should discourage the developer):
                                                                         b . addActionListener (
                                                                                                                                  ● static attribute is a class attribute
 Form2D o u t e r F= new Forme2D ( ) ;                                       new M y b u t t o n A c t i o n ( j t e x t ) ) ;
 Form2D . P oin t2D i n n e r P =                                    }
                                                                                                                                  shared with all instance (one common
                o u t e r F . new P o i n t 2 D ( ) ;           }                                                                 value) and static methods are callable
 i n n e r P . x =2;                                                                                                              without object instantiation.
                                                                c l a s s MybuttonAction implements                               Exemple :
                                                                                 ActionListener {
                                                                                                                                    - Integer . parseInt ("12"); used without
    -If public and static , inner class can be                                                                                    instantiation of an Integer object.
                                                                             public void
instantiated from outside without instanti-                                                                                         - Math.Pi used without instantiation of a
                                                                              actionPerformed ( Action e ){
ation of the outer class:
                                                                                j t e x t . setText (" c l i c k e d " ) ;        Math object.
 Form2D . P o i n t 2 D S t a t i c i n n e r P =                             }
                new Form2D . P o i n t 2 D S t a t i c ( ) ;    }                                                                 ● static applied only to attribute,
 i n n e r P . x =2;
                                                               ● to declare and instantiate at the same                           methods and inner class. Local variable
but can only access static member methods                      time a new class, based on a parent class                          can not be static (a nonsense).
of outer class:                                                or interface.
                                                                                                                                  ● static attribute and method can be
 // I n n e r c l a s s                                        ● use for encapsulation and concise code,
 s t a t i c c la ss Point2DStatic {
                                                                                                                                  accessed through an instance of the class,
                                                               if only one instance of the class is needed.
         int x , y ;                                                                                                              but it is a bad design:
                                                               (Exemple: a class implementing ActionLis-                           // Bad c o d e !
         public String toString () {                           tener to handle the events on a JButton.)                           I n t e g e r badCode = new I n t e g e r ( 1 ) ;
         r e t u r n " [ "+ x +" , "+ y +" ] " ;                                                                                   i n t a = badCode . p a r s e I n t ( " 12 " ) ;
         // no more a c c e s s t o c o l o r !
                                                               Note: An anonymous class has access to                              // Good c o d e s h o u l d be
         }                                                     the members of its enclosing class.                                 i n t a = I n t e g e r . p a r s e I n t ( " 12 " ) ;
 }
Demo:_innerClass                                                                                                                  Note: static method and static inner
                                                                                                                                  class can only call other static attributes
                                                                                                                                  and methods of the (outer) class, since no
                                                                                                                                  object instantiation!
                                                                                                                                  Demo:_modifierStatic
Java essentials
by l.cuvillon
Upcast/Downcast                                                 Runtime Polymorphism
 c l a s s Animal {                                              A n i m a l a n i m a l 1 = new A n i m a l ( ) ;
         i n t l e v e l =0;                                     A n i m a l a n i m a l 2 = new Dog ( ) ;
                                                                 A n i m a l a n i m a l 3 = new Cat ( ) ;
         p u b l i c void speak (){
           System . o u t . p r i n t l n ( " ? ? ? ? ? " ) ;    animal1 . speak ( ) ;        // " ? ? ? ? ? "
         }                                                       animal2 . speak ( ) ;        // " Wouaf "
 }                                                               animal3 . speak ( ) ;        // " Miaou "
                                                                ● At run time, method is called based on
 c l a s s Dog e x t e n d s A n i m a l {                      the actual object and not the type of the
         i n t l e v e l =1;                                    reference:
         @Override                                                - animal2.speak() call the method of the
         p u b l i c void speak (){                             class Dog and not of the reference type An-
           System . o u t . p r i n t l n ( " wouaf " ) ;       imal.
         }
                                                                C++: only if base method is virtual .
         p u b l i c v o i d b a r k ( ) {}                     Note:
 }
                                                                ● at compilation, call validity is checked
                                                                based on the reference type:
 c l a s s Cat e x t e n d s A n i m a l {
                                                                 - animal2.bark() invalid, since the class
         @Override
         p u b l i c void speak (){                             Animal has no such method.
           System . o u t . p r i n t l n ( " Miaou " ) ;       ● attribute is resolved based on the type of
         }
                                                                reference and not the actual object, if an
 }
                                                                identical attribute in parent and subclass:
Dog pluto = new Dog();                                           - animal2. level // value is 0
Upcast to the supertype:                                         - pluto . level      // value is 1
 Animal animal1 = ( Animal ) p l u t o ;
 Animal animal1 = p l u t o ;
                                                                Demo:_classPolymorphism
● always possible and the (cast) is faculta-
tive.
● Upcast allow writing generic code:
 public c l a s s AnimalTrainer {
   p u b l i c v o i d c a l l ( Animal a n i ){
              ani . speak ( ) ;     }
 }
 trainer . c a l l ( pluto );
 t r a i n e r . c a l l ( grosMinet ) ;
Downcast to subtype:
 if    ( a n i m a l 1 i n s t a n c e o f Dog )
 {
      Dog dogy = ( Dog ) a n i m a l 1 ;
      dogy . b a r k ( ) ; //now , v a l i d         call
 }
 // Note : a n i m a l 1 . b a r k ( ) i n v a l i d ,
 // c l a s s A n i m a l h a s no b a r k ( )
● the (cast) operator is mandatory.
● only possible if the objet belongs to the
subclass. To be tested with:
  - instanceof Dog             //true or false
 - ani1 . getClass (). equals(Dog.class))
Demo:_classPolymorphism
Note: downcast of an array is not allowed
(all elements may not be of downcast type).