You are on page 1of 205

Java

Object Oriented Programming


Basic OOP
• Object-oriented programming (OOP) is a method of programming
based on a hierarchy of classes, and well-defined and cooperating
objects
Class
• A class is a structure that defines the data and the methods to work
on that data
• When you write programs in the Java language, all program data is
wrapped in a class, whether it is a class you write or a class you use
from the Java platform API libraries
Objects
• An instance is an executable copy of a class
• Another name for instance is object
• There can be any number of objects of a given class in memory at any
one time
Class vs Object
• Class: A class is a blueprint that describes the states and/or
behaviors that objects of its type support
• Object: An object is an instance of a class. Objects have states and
behaviors. E.g. Object states have values and/or Objects call their
methods
Interface
• In the Java programming language, an interface is a reference type,
similar to a class, that can contain only constants, method
signatures, default methods, static methods, and nested types
• Method bodies exist only for default methods and static methods.
Interfaces cannot be instantiated—they can only be implemented by
classes or extended by other interfaces
Programming Contracts
• Implementing an interface allows a class to become more formal
about the behavior it promises to provide
• Interfaces form a contract between the class and the outside world,
and this contract is enforced at build time by the compiler
• If your class claims to implement an interface, all methods defined
by that interface must appear in its source code before the class will
successfully compile
Data Types
Java Data Types
• There are 2 basic categories of Java variables:
 Primitive variables
 Reference variables
Primitive Data Types
• 8 types in Java:
Data type range of values
Be careful with char!
Naming identifiers
Examples
Java reserved words
Examples
Reference Variables
• Also known as: Object Variables
• Default value -> null
References Vs Values
Wrapper Classes
Autoboxing - Unboxing
Java Basics
Java program execution
Java – Compile and Run
• Compile one java file: javac Student.java
• Compile two java files: javac Student.java StudentTester.java
• Compile all java files in current directory: javac *.java
• Run a Java class file: java StudentTester
Important Notes
• The Java compiler is smart enough to compile all source files that
are needed by the source files that you specify. For example, the
StudentTester class requires the Student class. When you compile
StudentTester.java, the compiler automatically compiles
Student.java.
• The javac command takes file names as input. The java command
takes a class name, without the .java or .class extension.
Java class
Package
• Every class belongs to a package
• Declaring a class in a package can be achieved directly, or even
indirectly without the presence of a package. In this case the default
package is used.
• If a package is declared, then it is the first declaration in code (only
exception -> comments)
• There can be only one package declaration for a specific class
Packages and Directories
• Package hierarchy is preserved also in file directory hierarchy
• The base project file directory can be placed anywhere in a file
system. Its subfolders, regarding its packages, should retain their
order.
Example
Comments
• They can appear anywhere inside source code file
• Single line comments and multi-line comments
End of line comments
Question
• What about comments inside code?
Class declaration
• Access modifiers
• Non-access modifiers
• Class name
• Extended class if present
• Implemented Interfaces (all) if any
• Class body:
 Fields (if any)
 Methods (if any)
 Constructors (if any)
 Inner classes (if any)
Example
Example
Top level Class Vs Nested
• A class that is not contained inside another class is named «Top
level» class
• A class whose code is contained inside another class is named
«Nested» class
Take a note!
• In every Java source code file there can be only one Top level public
class, or interface
• Nevertheless, a java source code file can contain a limitless number
of classes and/or interfaces (order of appearance does not make any
difference)
Fully qualified names
• For a class or an interface, fully qualified name is the combination of
the package name, followed by a dot and then the class or the
interface name
Import statements
• Inside the same package both classes and interfaces can use their
members without any (package) prefix
• However, in order to use classes and interfaces from other packages,
we need to declare their fully qualified name
• Using imports statements helps us use simple class and interfaces
names without specifying fully qualified names
• Import statements are always after the package declaration and
before the beginning of the class or interface
Example
Import usage 1/2
Import usage 1/2
Importing Packages and Classes
Remark
• Using the asterisk (*) special character we may import all classes
and interfaces inside this package
• However, using (*) does not import classes and interfaces of its
subpackages
Remark
• There is only one case where the import is not required for a specific
package
• This is the case of the java.lang package
• All classes and interfaces inside java.lang package are automatically
imported in each class and interface
Be careful for special cases
What happens with the default
package?
Static imports
• We can also import members of a class, such as variables and
methods
• To accomplish this:
 These members should be declared as static
 In the import statement declaration we should use «import static»

• E.g. import static com.unipi.talepis.MyClass.AFM;


• Or ever all static members using: import static com.unipi.talepis.*
Example
Naming conventions 1/6
Naming conventions 2/6
Naming conventions 3/6
Naming conventions 4/6
Naming conventions 5/6
Naming conventions 6/6
Executable Vs Non-executable
Java classes
• What is the difference?
• Think about it!
The main method
Did you know?
What will happen?
Access Modifiers
Access modifiers
• Access modifiers define members’ access levels in Java
• Access modifiers:
 private
 default (package)
 protected
 public
Access modifiers explanation
Access modifiers Table 1
Access modifiers Table 2
Example 1
Example 2
Private Access Modifier
Default Access Modifier
Protected Access Modifier
Public Access Modifier
Non-access
Modifiers
Non-access modifiers
• Reserved Java words that do not deal with access levels
• They are the following:
 abstract
 static
 final
 synchronized
 volatile
 strictfp
 transient
 native
Synchronized
• Used only in methods
• Denotes that different threads cannot access the synchronized
method at the same time
Volatile
• Used with variables
• Denotes that a volatile variable can be “safely” accessed through
different threads
• The variable is kept in memory (only)..!
Strictfp
• Used in classes, interfaces and methods
• Denotes that calculations that involve decimals will be the same in
all platforms
Transient
• Used with variables
• Denotes that a variable will not get serialized when its object is
serialized
Native
• Used in methods
• Denotes that the methods can use libraries and methods from other
programming languages, such as C και C++
Abstract
• Used in classes and methods
• Interfaces are abstract by default (but it is not wrong to declare them
abstract)
• Classes:
 We cannot create an instance of them
 Used basically in classes that are supposed to be inherited by others

• Methods:
 These methods have signature but no body
 Their implementation is most usually given by child classes
 A method that has {} but no source code is not abstract!

• An abstract class can have no abstract methods


• If an abstract method exists, then its class should also be declared
abstract
Notes about abstract
• A class cannot be declared both abstract and final
• If a class contains one or more abstract methods, then the class
should be declared abstract, or else a compile error will be thrown
• An abstract class may contain both abstract methods as well normal
methods
• An abstract class does not need to contain abstract methods
• Abstract methods can never be final
• Any class that extends an abstract class must implement all the
abstract methods of the super class unless the subclass is also an
abstract class
• Abstract methods end with a semicolon
Final
• Used in classes, variables and methods
• Interfaces are abstract by default, so they cannot be declared final
• Class:
 A final class cannot be extended

• Methods:
 A final method cannot be overridden by a sub class

• Variables:
 In a final variable a value can be given only once. (Be careful: What
happens with reference variables?)
Static 1/2
• Used in nested classes, nested interfaces, methods and variables
• Nested class:
 Static inside a top level class
 Cannot access non static members
 Refer to them using the outer class name

• Nested interfaces:
 Are by default static so there is no need to declare them static
Static 1/2
• Methods:
 Belong to the class, not to the object
 Cannot access instance members
 Refer using the outer class name
 Static methods exist both in classes and interfaces (Java 8+)

• Variables:
 Belong to the class, not to the object
 Are shared between instances. We don’t need object instantiation for their
existence
 All interface variables are by default static
 In Java the used way to declare a constant is use a final static variable
 Accessing can be achieved both through the class but also through the
instance (the second way is not recommended)
Accessing between static and
non-static members
• A static method and a static variable cannot access not statica ones
• The opposite is correct. Non static members can access static ones
• Be very careful!:
 Even a null object can still access static variables and/or methods. This is
why we won’t get a NullPointerException in this case. Nevertheless, such
code should be avoided…
Static Vs Non-static
Variables in Java
Variable scope
• Java variables can be characterized by their scope
• Based on their scope we have 4 categories of Java variables:
 Local variables (variables inside methods)
 Method parameters
 Instance Variables
 Class Variables (Static variables)
Local variables – Method
parameters
• Have very short “life time” since they live inside methods, and even in loops
• Always look at the block ( { } ) inside which they are declared
• No access to them outside their block
Instance variables
• Inside class, outside methods
• Without static keyword
• All non static methods have access
• Each object has its own ones
Class variables
• Inside class, outside methods
• Using static keyword
• All methods (static and non static) have access
• Belong to the class. No object can have its own ones
Same names for variables
• We cannot have an instance variable and a static variable with the
same name
• We cannot have a method parameter and a local variable with the
same name
• We can have a static variable and a local variable with the same
name. Also an instance variable and a local variable with the same
name. But you should take care!..
Additional
Knowledge 1
Method return statement
Variable Arguments (varargs)
• Java 5+
• Are actually arrays
• They allow as to give arguments of any length to a method (of the same
type of course)
• Each method can have up to one vararg parameter
• If a varargs exists then it should be the last parameter of the method
(why?...)
Java instanceof Operator
• Binary operator
• true – false
• Used with objects
• Checks whether an object is of a specific Type (including interfaces)
• Used many times in order to avoid ClassCastException
• General type:
 (object) instanceof (type)
Example 1/2
Example 2/2
Result
this and super
• Use this keyword in order to access members of the “current” class
• Use super to access members of the parent class
• Both words can be used for static and non static members
• Can also be used with constructors (Advanced Java)
Example
Example
Example
Example – Pay attention!
Method overloading
Constructors
• Used to instantiate objects
• Have the same name as the class, yet, BE CAREFULL, what makes them differ
is the fact that they do not return anything!!!
• Accept overloading
• Support all levels of access modifiers
Default constructors
Invoking constructor from
another constructor…
• Using the keyword this
Constructors - Important
Initializer Block (Advanced)
• Τhe initializer block is a piece of code that is always executed when a
new object is created
• We don’t know which constructor is going to be used. However, the
initializer block will always be executed
• It is executed before constructor
Java API
Java Strings
• Sequence of characters
• Inside " "
• Every String is an object
• There are many ways to declare a String (String s = "Hello";)
• Handling String correctly can help:
 Reduce errors
 Code optimization!
 Multithreading enviroments
String pool
• For code optimization Java incorporates a String pool
Creating Strings

• Even with the existence of a String Pool, if you use the “new”
keyword, a new String will be created!
String handling methods
Important!
• String is Immutable
• All String methods do not change its actual String content!
String comparison
• Be very careful. Many mistakes by programmers
• == is used to compare variables address
• Some times == can give as equality due to the String Pool. It should
be avoided!
• Use the equals() method
Be careful!
Mutable Strings
• Basic class: StringBuilder
• Belongs to package: java.lang
• Used either when we have “big” strings or when we make many
changes to the string
• In this way we may optimize our code!
• StringBuilder constructor accepts many overloads (to use them)
StringBuilder Methods
StringBuilder Vs StringBuffer
• Class StringBuffer offers almost the same functionality as
StringBuilder
• Basic difference is that StringBuffer is synchronized and thus
«thread safe»
• Nevertheless, synchronized comes at a cost (time overhead)
Java ArrayList
• One of the most used classes in Java
• Tries to combine the benefits of (Arrays) and (Lists)
• Dynamic size
• Basic functionality:
 Add elements to the list
 Delete elements from the list
 Change elements of the list
 Access elements of the list
ArrayList Properties
ArrayList Creation
ArrayList – Add Items
ArrayList – Item Iteration
ArrayList – Item Iteration v2
using ListIterator
Exercise
• Using the aforementioned two ways of iteration inside an ArrayList
try to see if you can change the values of the elements while you
access them (inside the loop)
• Write down what you observe!
ArrayList - addAll() method
ArrayList – Access elements
Examples
Exercise
• Use the following two methods in ArrayList:
 toArray()
 clone()
Java Extras
Ternary Operator ?:
?:
• In computer programming, ?: is a ternary operator that is part of the
syntax for a basic conditional expression
• It is commonly referred to as the conditional operator, inline if (iif),
or ternary if
• Basic syntax:
condition ? value_if_true : value_if_false
• The condition is evaluated true or false as a Boolean expression
• The entire expression returns value_if_true if condition is true, but
value_if_false otherwise
examples

• result = testCondition ? value1 : value2

• int minVal = (a < b) ? a : b;


• String str1 = false ? “Yes, its ok" : “I am sorry";
Switch Vs If
Switch examples
Optional fields in for loop
Enhanced for loop (for-each)
Java for-each

• Since Java 1.5

for (Type item : iterableCollection) {


// Do something to item }
Examples (without foreach loop)

int[] intarray = new int[]{2,4,6,8};

for(int i=0;i<intarray.length;i++)
System.out.println(intarray[i]);
Examples (with foreach loop)

int[] intarray = new int[]{2,4,6,8};

for(int i : intarray)
System.out.println(i]);
Some limitations

int[] intarray = new int[]{2,4,6,8};

for(int i=0;i<intarray.length;i+=2)
System.out.println(intarray[i]);
More examples 1/2

String[] strarray = new String[]{"Maria","Pavlos","George"};

for(String s : strarray)
System.out.println(s);
More examples 2/2 (even
better…)

List<String> mylist = new


ArrayList<String>();
mylist.add("Hallo");
mylist.add("Students");
mylist.add("of");
mylist.add("Unipi");
for(String s : mylist)
System.out.println(s);
Wait! What was that strange <String>
in
List<String> mylist = new ArrayList<String>();
?

It is called Java Generics


And we will talk about this too..!
for Vs for-each
Java – Labeled Statements
• In Java we can use labels in the following cases:
Labeled break
Labeled continue
Summary
Branching statements
• Break
 Unlabeled
 Labeled

• Continue
 Unlabeled
 Labeled

• Return
 With value
 No value
Java Inheritance
Inheritance 1/3
Inheritance 2/3
Inheritance 3/3
Inheritance Notes
• In the Java language, classes can be derived from other classes,
thereby inheriting fields and methods from those classes
• A class that is derived from another class is called a subclass
• The class from which the subclass is derived is called a superclass
What can a Subclass do?
• The inherited fields can be used directly, just like any other
fields
• You can declare new fields in the subclass that are not in
the superclass
• The inherited methods can be used directly as they are
• You can write a new instance method in the subclass that
has the same signature as the one in the superclass, thus
overriding it
• You can declare new methods in the subclass that are not in
the superclass
Inheritance Example
IS-A vs HAS-A
• IS-A means is of type and denotes Inheritance
• HAS-A means composition between objects
Class Diagram
Java Method Overriding
• A method defined in a super class may be overridden by a method of
the same name defined in a sub class
• The overriding method has the same name, number and type of
parameters, and return type as the method that it overrides
Advantages of Inheritance
• Lower size of code for subclasses
• Easily modify methods and variables
• Expansibility
• Base class code testing
• Logical division of code
Object variables
Example
Through its class
Through its super class
Through the implementing
Interface
Through the Object class
Why do we have so many
capabilities?
Casting with
objects
What is Casting
• Using casting we can enforce a variable behave as another variable
• In class level casting occurs when there is a IS-A relationship
Example
Testing 1/2
Testing 2/2
Java Anonymous
Classes
Extending an existing class
Implementing an existing
interface
Using new without a variable
• Just use the instance, without the variable
• new Object()
• In this case, we actually have an anonymous variable, not a new
class
Examples
Extending an existing Class
Implementing an existing Interface
Simply using “new”
• We can also use a simple method returning an object
Using variables inside
anonymous classes
• An anonymous class has full access to member variables of its outer
class
• An anonymous class cannot access local variables that are not final
or “effectively final”
Examples
Anonymous class with no default
constructor
Anonymous class with instance
initializer
Declarations inside an
anonymous class
• Fields (instance, static need to be final and initialized)
• Extra methods (even if they do not implement any methods of the
supertype)
• Instance initializers
• Local classes (εσωτερικές τάξεις)
• We cannot include a nested interface…
Why anonymous object
• Used mostly as method parameters
 Classes or subclasses of a specific Type
 Implementing specific Interfaces

• Sometimes inside an expression

You might also like