Course 1 - Inscriere

advertisement
Course 1
Lesson 1. Introduction in Java
1.1 History
Java is a programming language created by James Gosling from Sun Microsystems
(Sun) in 1991. The first publicly available version of Java (Java 1.0) was released in
1995. Sun Microsystems was acquired by the Oracle Corporation in 2010. Oracle has
now the steermanship for Java. In 2006 Sun started to make Java available under
the GNU General Public License (GPL). Oracle continues this project
called OpenJDK.
Over time new enhanced versions of Java have been released. The current version
of Java is Java 1.8 which is also known asJava 8.
Java is defined by a specification and consists of a programming language, a
compiler, core libraries and a runtime (Java virtual machine). The Java runtime
allows software developers to write program code in other languages than the Java
programming language which still runs on the Java virtual machine. The Java
platform is usually associated with the Java virtual machine and theJava core
libraries.
1.2 Characteristics of Java
The target of Java is to write a program once and then run this program on multiple
operating systems.
Java has the following properties:




Platform independent: Java programs use the Java virtual machine as
abstraction and do not access the operating system directly. This makes
Java programs highly portable. A Java program (which is standard-compliant
and follows certain rules) can run unmodified on all supported platforms, e.g.,
Windows or Linux.
Object-orientated programming language: Except the primitive data types, all
elements in Java are objects.
Strongly-typed programming language: Java is strongly-typed, e.g., the types
of the used variables must be pre-defined and conversion to other objects is
relatively strict, e.g., must be done in most cases by the programmer.
Interpreted and compiled language: Java source code is transferred into the
bytecode format which does not depend on the target platform. These
bytecode instructions will be interpreted by the Java Virtual machine (JVM).
The JVM contains a so called Hotspot-Compiler which translates
performance critical bytecode instructions into native code instructions.

Automatic memory management: Java manages the memory allocation and
de-allocation for creating new objects. The program does not have direct
access to the memory. The so-called garbage collector automatically deletes
objects to which no active pointer exists.
1.3 Development process with Java
Java source files are written as plain text documents. The programmer typically
writes Java source code in an Integrated Development Environment (IDE) for
programming. An IDE supports the programmer in the task of writing code, e.g., it
provides auto-formating of the source code, highlighting of the important keywords,
etc.
At some point the programmer (or the IDE) calls the Java compiler (javac). The
Java compiler creates the bytecode instructions. These instructions are stored
in .class files and can be executed by the Java Virtual Machine.
1.4 Classpath
The classpath defines where the Java compiler and Java runtime
for .class files to load. These instructions can be used in the Java program.
look
1.5 Java installation
Please follow the instructions provided at this linkfor a full explanation on how to
install Java on your machine.
2. Exercise: Write, Compile and Run a Java program
Open a text editor which supports plain text, e.g, Notepad and write the following
source code:
Save the source code in your javadir directory with the HelloWorld.java filename. The
name of a Java source file must always equal the class name (within the source
code) and end with the .java extension. In this example the filename must be
HelloWorld.java, because the class is called HelloWorld.
To be able to run the class, first you have to compile the class. Open Windows
console and navigate to the folder wich contains the .java file and press the following
command:
After this command executes a new file is created HelloWorld.class, representing the
compiled class.
To run the class and see Hello World output, now enter the following command into
console:
Lesson 2: Principles of OOP in Java
2.1 Class
Definition:Template that describes the data and behavior associated with an instance
of that class.The class can be seen as the blueprint of an object. It describes how an
object is created.
In Java source code a class is defined by the class keyword and must start with a
capital letter. The body of a class is surrounded by {}.
The data associated with a class is stored in variables; the behavior associated to
a class or object is implemented with methods.
A class is contained in a Java source file with the same name as the class plus
the .java extension.
2.2 Object
Definition:An object is an instance of a class.
The object is the real element which has data and can perform actions. Each
object is created based on the class definition.
2.3 Inheritance
Inheritance is a fundamental concept of the Java language. It allows specific classes
to inherit the methods and instance variables of more general classes. This creates
code that is maintainable and emphasizes code reuse.
Inheritance allows a developer to create general classes that can then be used as
the foundation for multiple specific classes. For example, a program may be required
to have classes that represent animals. The animals that must be represented are
dogs, cats, and horses. All of these animal classes share some common elements. In
this simple example, each animal would have a weight, age, and color instance
variable.Each animal class would also have methods that allow it to do such things
as eat, rest, and move. These methods could be called eat(), rest(), and move(int
direction).This can be implemented without inheritance by creating a class for each
animal type and then defining each of the previously mentioned methods. This
implementation approach will work but has a few drawbacks. Since each type of
animal eats, rests, and moves very similarly, there will be a lot of duplicated code
between each class. Duplicated code makes a program hard to maintain. If a bug is
found in one class, the developer must remember to go find it in every other class
that has a copy of that code.
2.3.1 Inheritance Example:
2.4 Abstract Classes
An abstract class is different from a concrete class because it cannot be
instantiatedand must be extended. An abstract class may contain abstract methods.
Abstract methods are methods that are not implemented. They have a valid method
signature but must be overridden and implemented in the class that extends the
abstract class.
The following is an example of an abstract class:
The preceding example is an abstract class for a music player. This is intendedto be
the base class for different music-playing devices such as MP3 players or CD
playersThis class provides some functionality with the changeVolume() method. It
also contains two abstract methods. An abstract method can only exist in an abstract
class. The abstract keyword is used to mark a method as such. Every abstract
method must be implemented in the subclass that extends it. The purpose of an
abstract method is to define the required functionality that any subclass must have. In
this case, any music player must be able to play and stop. The functionality cannot
be implemented in the MusicPlayer class because it is different from player to player.
The following example is of two classes extending the MusicPlayer class:
2.5 Interfaces
Interfaces are used in the Java language to define a required set of
functionalitiesfrom the classes that implement the interface. Unlike extending base
classes, a class is free to implement as many interfaces as needed. An interface can
be thought of as an abstract class with all abstract methods. When a class
implements an interface, it is required to implement all of the methods defined in the
interface. Interfaces are used to create a standard public interface for similar items.
This enables code to be more modular. The interfacekeyword is used to create an
interface in the next example.
The preceding example is a very basic interface for a phone. The next example
demonstrates this interface being implemented by a cell phone class and a landline
phone. The keyword implements is used to implement an interface.
When an interface is implemented, all of its methods must then be implemented in
that class. It is possible to implement multiple interfaces. When more than one
interface is being used they are separated in a comma-delimited list. When multiple
interfaces are used, all of the methods defined in each one must be implemented.
Any unimplemented methods will cause the compiler to generate errors. The
following is an example of a class implementing two interfaces:
2.6 Encapsulation
Encapsulation is the concept of storing data together with methods that operateon
that data. Objects are used as the container for the data and code. This section
discusses the principles of encapsulation and how it should be applied as a
developer.
The fundamental theory of an object-oriented language is that software is designed
by creating discrete objects that interact to make up the functionality of the
application. Encapsulation is the concept of storing similar data and methods
together in discrete classes. In many nonobject-oriented languages there is no
association between where the data is and where the code is. This can increase the
complexity of maintaining the code because oftentimes the variables that the code is
using are spread apart over the code base. Bugs in the code can be hard to find and
resolve due to different remote procedures using the same variables. Encapsulation
tries to solve these problems. It creates easier to read and maintainable code by
grouping related variables and methods together in classes. Object-oriented software
is very modular, and encapsulation is the term used for creating these modules.
Encapsulation allows for information hiding.
A well-encapsulated class is one that has a single clear purpose. This class should
only contain the methods and variables that are needed to fulfill its purpose.
Forexample, if a class was intended to represent a television, it should contain
variables such as currentChannel,volume, and isPoweredOn. A Televisionclass
would also have methods such as setChannel(int channel) or setVolume(int volume).
These variables and methods are all related. They are specific to the properties and
actions needed to create a Television class. The Television class would not contain
methods such as playDVD(); this should be contained in a separate DVD class.
Encapsulation is about creating well-defined classes that have a clear purpose.
These classes contain all the data and methods needed to perform their intended
functions.
2.7 Polymorphism
The word polymorphism comes from the Greeks and roughly means “many forms.” In
Java, polymorphism means that one object can take the form, or place of, an object
of a different type. Polymorphism can exist when one class inherits another. It can
also exist when a class implements an interface.
2.7.1 Polymorphism via Class Inheritance
Polymorphism happens when a certain object type is needed and an object of that
type or another more specific object is accepted in its place.
An object is a more specific type of another object when it extends that object. For
example, a method may require a Human object. When the Child and Adult classes
extend the Human class they would each possess all of the functionality of a Human,
plus all the more specific functionality of their age. The Child and Adult objects are
guaranteed to have all of the methods that a Human object has because they gain
them through inheritance. Therefore both the Child and Adult objects would satisfy
any operation that required a Human object. This could be continued further with the
Shannon and Colleen classes, which each extend the Adult class. Each of the
objects created from the Shannon and Colleen classes would have the functionality
of the more general Adult and Human classes, and can be used anywhere a Human
or Adult object is required.
2.7.2 Polymorphism via Implementing Interfaces
The application of polymorphism is not limited to class inheritance. Polymorphism
can also be applied to the objects of classes that implement interfaces. When a
classimplements an interface, it is then required to implement all of the methods that
the interface contains. By doing this, the class is guaranteed to have the functionality
that the interface defines. This allows the objects created from these classes
topolymorphically behave as the data type of the interface. An interface called
Display can be used for classes that have the ability to display text on a screen. This
interface contains two methods. One method is used to display text, and the second
is used to get the text that is currently being displayed. Any class that implements this
interface is declaring to other objects that it has the functionality of a Display. By
implementing this interface the class is required to then implement every method that
the interface contains.Since the object was created from a class that implements the
Display interface, it is guaranteed to have the functionality of a display. The object
has an is-a relationship with Display. This object can now masquerade as an object
of the Display type. An object can polymorphically act as any interface that its class
or any superclass implements.
Polymorphism and interfaces are very powerful tools. They are used extensively on
large projects. As a professional developer, it is a good idea to study design
patterns.This will provide common reusable software designs that make use of the
concepts in this chapter. A good developer not only understands all of the basic
concepts, but also knows how to best use them.
2.7.3 Polymorphism in Code
When one specific object can be used as another general object polymorphically, the
specific object can be used in place of the more general one without being cast. For
example:
TypeC extends TypeB, and TypeB extendsTypeA, anytime an object type of TypeA
or TypeB is needed, TypeC can be used. The following code segment shows an
example of this:
2.8 Override and Overload
Any time you have a class that inherits a method from a superclass, you have the
opportunity to override the method (unless, as you learned earlier, the method is
marked final). The key benefit of overriding is the ability to define behavior
that'sspecific to a particular subclass type. The following example demonstrates a
Horse subclass of Animal overriding the Animal version of the eat() method:
The rules for overriding a method are as follows:












The argument list must exactly match that of the overridden method. If
theydon't match, you can end up with an overloaded method you didn't intend.
The return type must be the same as, or a subtype of, the return type
declaredin the original overridden method in the superclass.
The access level can't be more restrictive than the overridden method's.
The access level CAN be less restrictive than that of the overridden method.
Instance methods can be overridden only if they are inherited by the subclass.
A subclass within the same package as the instance's superclass can override
any superclass method that is not marked private or final. A subclass in
adifferent package can override only those non-final methods marked public or
protected (since protected methods are inherited by the subclass).
The overriding method CAN throw any unchecked (runtime)
exception,regardless of whether the overridden method declares the exception
The overriding method must NOT throw checked exceptions that are newor
broader than those declared by the overridden method. For example, amethod
that declares a FileNotFoundException cannot be overridden by amethod that
declares a SQLException, Exception, or any other non-runtimeexception
unless it's a subclass of FileNotFoundException.
The overriding method can throw narrower or fewer exceptions. Just
becausean overridden method "takes risks" doesn't mean that the overriding
subclass exception takes the same risks. Bottom line: an overriding method
doesn'thave to declare any exceptions that it will never throw, regardless of
what theoverridden method declares.
You cannot override a method marked final.
You cannot override a method marked static. We'll look at an example in afew
pages when we discuss static methods in more detail.
If a method can't be inherited, you cannot override it. Remember
thatoverriding implies that you're reimplementing a method you inherited!
Forexample, the following code is not legal, and even if you added an
eat()method to Horse, it wouldn't be an override of Animal's eat() method.
Overloaded methods let you reuse the same method name in a class, but with
different arguments (and optionally, a different return type).
Rules:





Overloaded methods MUST change the argument list.
Overloaded methods CAN change the return type.
Overloaded methods CAN change the access modifier.
Overloaded methods CAN declare new or broader checked exceptions.
A method can be overloaded in the same class or in a subclass. In other
words,if class A defines a doStuff(int i) method, the subclass B could define
adoStuff(String s) method without overriding the superclass version thattakes
an int. So two methods with the same name but in different classescan still be
considered overloaded, if the subclass inherits one version of themethod and
then declares another overloaded version in its class definition.
Download