Index
1. OBJECT-ORIENTED PROGRAMMING.
1.1. Introduction to Programming
Object Oriented.
1.2. Classes.
1.3. Creation of a class.
1.4. Objects
1.5. Practical Example with Objects.
1.6. Practical Example with Objects II.
1.7. Interaction between the elements.
1.8. Example Interaction between elements.
1.9. Interfaces II.
1.10. Peculiarities of Java.
Campus Impúlsate | info@[Link]
Content
1.1. Introduction to Programming
Object Oriented.
Nowadays, the object-oriented paradigm is the most used for programming.
we can practically find it in most programming languages
most used: Java, PHP, C++, etc.
Object-oriented programming (OOP) is nothing more
a programming paradigm that innovates the way results are obtained.
Objects manipulate input data to obtain output data.
specific, where each object offers a special functionality.
Many of the predefined objects of current programming languages
they allow grouping in libraries, however, many of these languages
allow the user to create their own libraries.
OOP is based on several techniques, including inheritance, cohesion, abstraction,
polymorphism, coupling, and encapsulation.
In a more classic programming environment, the problem or system being addressed
analyzing is divided into functions, each function only operated with its parameters of
input and did not modify information external to it.
To carry out the analysis with object-oriented programming, one must have
It is said that programs are coded thinking about objects that interact.
The objects will have certain properties and will be able to do certain
things through the methods (functions) that have been defined in templates
called classes.
If a good design of the objects and their interaction is made, they can be used in new ones.
easily programs and projects, promoting reusability.
Throughout the history of computer science, different paradigms have emerged.
programming. First, sequential programming appeared, which consisted of
sequences of statements that were executed one after the other. The assembly language or the
COBOL language are sequential languages. So the concept of did not exist
function, which later appeared in procedural languages, such as BASIC or
The C. The evolution didn't stop here, and continued until the most widespread paradigm in the
current events: object-oriented programming. Smalltalk, C++ or Java belong to
this new generation.
Campus Impúlsate | info@[Link]
Each new paradigm has extended the previous one, so we can find the
characteristics of a sequential language in a procedural one, and those of one
procedural to an object-oriented.
A little history
JAVA was created as a programming tool to be used in a project
the set-top box in a small operation called the Green Project at Sun
Microsystems in the year 1991. The Green Team, which is made up of 13 people.
counting with James Gosling at the helm, worked for 18 months on Sand Hill Road
in Menlo Park in its development.
The language was initially named Oak (a name given because
to an oak tree that was outside the office), then it changed its name to 'Green'
after discovering that Oak was a trademark of graphics card adapters, thus
which later changed its name to JAVA.
It is frequented by some of the team members. What is unclear is whether
it is an acronym or not, though there are certain sources that indicate that they are the
initials of their designers: James Gosling, Arthur Van Hoff, and Andy Bechtolsheim.
Others bet on the following acronym, JustAnotherVagueAcronym.
ambiguous acronym more). The hypothesis that sounds the strongest is that the name of
JAVA refers to a type of coffee that was served at a nearby bar, hence the
The icon could be a cup of coffee releasing steam. Another hint could be the first 4.
bytes of the .class files, bytes that in hexadecimal give us the following 0xCAFEBABE.
And despite all these theories, it seems that the name was taken from a random list.
What Gosling intended to do was implement a virtual machine (VM) with a
structure and language that was similar to that of C++. Between the months of June and July of
1994, after an enormous multi-day session with John Gaga, James Gosling, Patrick
Naughton, Wayne Rosing, and Eric Schmidt, the team redirected the platform towards the
web environment. They anticipated that the arrival of Mosaic (a web browser) would make the internet
became an interactive medium. Naughton got to work and created a
a web browser prototype called 'WebRunner', which would later be known as
the name of HotJAVA.
Back in 1994, the high-ranking officials at Sun were given a demonstration of HotJAVA.
The first version of JAVA could be downloaded for the first time back in 1994, but
It was not until May 23 of the following year that the public versions were seen.
JAVA and HotJAVA, the Web browser. The event was announced by John Gage, the
Scientific Director of Sun Microsystems. Furthermore, the event had a surprise, Marc
Andreessen, executive vice president of Netscape, announced that his browser would support
On January 9, 1996, SUN founded the JavaSoft group to take charge of everything
part of technological development. It was two weeks later when the first version
was published.
The initial promise, if we remember, was the one that said "Write Once, Run Anywhere".
making the programming language platform-independent, and
providing a virtual execution machine for those platforms more
popular, thus allowing the code to be executed on any platform.
Campus Impúlsate | info@[Link]
The runtime environment was relatively safe, so the main
browsers began to support the execution of JAVA applets within the
own websites.
Java has undergone numerous changes since its original version, JDK 1.0, so
as a significant increase in the number of classes and packages that make up the library
base.
Since J2SE version 1.4, all changes in the language have been regulated by the 'JAVA
Community Process (JCP), which is based on Java Specification Requests (JSRs) for
propose future changes to the platform. The language is specified in the JLS (the
JAVA Language Specification). Changes in the JLS are managed in JSR 901.
JDK 1.0 (January 23, 1996) - First release: and press release
JDK 1.1 (February 19, 1997) - Main additions included: released
press
• an intensive restructuring of the AWT (Abstract Windowing Toolkit) event model
Toolkit
• inner classes
• JavaBeans
• JDBC (Java Database Connectivity) for database integration
• RMI (Remote Method Invocation)
J2SE 1.2 (December 8, 1998) - Codename Playground. Both this and the
the following versions were collected under version Java 2 and the name "J2SE" (Java 2
Platform, Standard Edition), replaced JDK to differentiate the base platform from
J2EE (Java 2 Platform, Enterprise Edition) and J2ME (Java 2 Platform, Micro Edition).
Other added improvements included:
• the reserved keyword strictfp
• reflection in programming
• a graphical API called Swing, which was integrated into the basic classes
• the Sun virtual machine (JVM) that was equipped with a JIT (Just-In-Time) compiler
in Time) for the first time
• Java Plug-in
• Java IDL, an implementation of IDL (Interface Definition Language) for
interoperability with CORBA
• Collections
J2SE 1.3 (May 8, 2000) - Codename Kestrel. The most notable changes
were
• the incorporation of the HotSpot JVM virtual machine (which was released
initially in April 1999, for the JVM of J2SE 1.2)
• RMI was modified to be based on CORBA
• JavaSound
• the Java Naming and Directory Interface (JNDI) was inserted into the package that
contains the main libraries (which were previously available
through an extension)
• Java Platform Debugger Architecture (JPDA)
Campus Impúlsate | info@[Link]
J2SE 1.4 (February 6, 2002) - Codename Merlin. It was the first release.
of the JAVA platform developed under the control of the JAVA community as JSR 59.
The most notable changes were:
• The insertion of the reserved keyword assert (Specified in JSR 41.)
• Regular expressions designed in the style of regular expressions from
Perl programming language
• Chaining of exceptions, which allows one exception to encapsulate the
original low-level exception.
• non-blocking NIO (New Input/Output) (Specified in JSR 51.)
• Logging API (Specified in JSR 47.)
• An I/O API for reading and writing images in JPEG or PNG formats
• An XML parser and an XSLT processor specified in JSR 5 and JSR 6
• Cryptographic extensions (JCE, JSSE, JAAS) and integrated security
• Java Web Start included (The first release took place in March 2001)
for J2SE 1.3) (Specified in JSR 56.)
J2SE 5.0 (September 30, 2004) - Codename: Tiger. (Originally numbered
1.5, this notation is still used internally.) Developed under JSR 176, Tiger
incorporated a large number of new features
• Templates (generics) provide type safety during
the compilation time for collections and eliminates the need for the
majority of type casting. (Specified by JSR 14.)
• Metadata—also known as annotations, grants to structures of
language such as classes or methods, can be tagged with some
additional data that can be processed later by utilities of
metadata process. (Specified by JSR 175.)
• Autoboxing/unboxing - Conversions between primitive types (int) in a way
automatic and also classes of primitive wrapper (Integer). (Specified by
JSR 201.)
• Enumerations —the reserved word 'enum' creates a 'typesafe', a list
sorted by values ([Link], [Link]...). "In the past", this could only
be made by constants of type int or by classes built manually
(enum pattern). (Specified by JSR 201.)
• Varargs (variable number of arguments) - The last parameter can be
indicated by the type of the variable and use three dots to indicate the name
from the variable (e.g. void drawtext(String... lines)). When the method is called
with an indeterminate number of parameters, these parameters will be
stored in an array.
• Enhanced for loop - The syntax for the for loop has been extended,
that it is possible to iterate over any class that implements Iterable, such as the
standard Collection class in the following way:
Impulse Campus | info@[Link]
In this example, the for loop iterates over the Iterable widgets object, assigning in order,
each of its elements to the variable w, and calling the display() method of each one
of them. (Specified by JSR 201.)
Java SE 6 (December 11, 2006) - Codename Mustang. It was under development.
under JSR 270. For this version, SUN changed the name "J2SE" to Java SE and removed
the '.0' of the version number. It is available at [Link]
The most notable changes in this version are:
• Incorporates a new framework and APIs that enable the combination.
from JAVA with other programming languages such as PHP, Python,
Ruby and JavaScript.
• It also incorporates the Rhino engine, from Mozilla, an implementation of JavaScript.
inside Java.
• Fully includes a Web Services client and supports the latest
specifications for web services, such as JAX-WS 2.0, JAXB 2.0,
STAX and JAXP.
• Improvements in the graphical interface and overall performance.
Java SE 7—Code name Dolphin. It was still in the early stages of
planning back in 2006. Its final release was in July 2011.
• XML supported in the language itself.
• A new concept of "superpackage".
• Support for closures.
• Standard annotations for detecting software failures.
Unofficial:
• NIO2.
• Java Module System.
• Java Kernel.
• A new API to be able to use Days and Dates, which is a replacement
from the old Date and Calendar classes.
• Possibility of operating with BigDecimal classes using operands.
Java SE 8 was released in March 2014. It is worth highlighting:
• Fully incorporate the JavaFX library.
• Various security improvements.
• Improvements in concurrency.
• Add functionality for functional programming through expressions
Lambda.
• Improves JavaScript integration.
• New APIs for handling dates and time.
Java SE 9 was released in 2017. It is worth mentioning:
• Modularization of the JDK under Project Jigsaw (Platform module system)
Java.
• Java Shell (a Java REPL).
• Early compilation.
Campus Impúlsate | info@[Link]
• XML Catalogs.
• More concurrency updates. Includes a Java implementation of
Reactive Streams, which includes a new class of flow that includes the interfaces
previously provided by Reactive Streams.
• Variable handles: define a standard means to invoke the equivalents of
various [Link].
• Java Linker: create a tool that can assemble and optimize a set
of modules and their dependencies in a custom image at runtime
execution. Effectively, it allows the production of a fully executable.
usable, including the JVM to run it.
• JavaDB has been removed from JDK.
• HiDPI Graphics: automatic scaling and size.
Java SE 10 was released on March 20, 2018, with twelve confirmed new features.
Among these characteristics are:
• Local variable type inference.
• Experimental JIT compiler based on Java. This is the integration of
Graal dynamic compiler for the Linux x64 platform.
• Application class data exchange. This allows classes of
applications are placed in the shared folder to reduce the start and the
footprint of Java applications.
• Time-based versions.
• Complete parallel GC for G.
• Garbage collector interface.
• Additional extensions of Unicode language tags.
• Root certificates.
• Local handshakes.
• Stack assignment in alternative memory devices.
• Remove the native header generation tool - javah
• JEP 296: Consolidate the JDK forest into a single repository.
Java SE 11 was released in September 2018, and the version is currently open for
correct errors. Among others, Java 11 includes a number of new features, such
how:
• Dynamic class file constants.
• Epsilon: a garbage collector without operation.
• local variable syntax for lambda parameters.
• Low overhead stack profile.
• HTTP client (standard).
• Transport Layer Security (TLS) 1.3.
• Flight recorder.
• ZGC: a scalable low-latency garbage collector.
• The JavaFX, Java EE, and CORBA modules have been removed from the JDK.
• Disapproved the Nashorn JavaScript engine.
• Compatibility with Unicode 10.0.0 (while the current version is Unicode
11.0.0, only available in Java 12.
Campus Impúlsate | info@[Link]
Java SE 11 was released in September 2018
The Java Virtual Machine Specification defines it as:
JDK 12 was released on March 19, 2019. Among other things, Java 12 includes a series of
new features, such as:
• Shenandoah: A Low-Pause Garbage Collector (Experimental)
• Microbenchmark Suite.
• Change expressions (preview).
• JVM constants API.
• a AArch64 port, not two.
• Default CDS files.
• Mixed Abortable Collections for G1.
• Quickly return the unused committed memory from G1.
An imaginary machine implemented through software emulation in a
real machine. The code for the Java virtual machine is stored in .class files,
each of which contains at least the code for a public class.
The Java Virtual Machine specification provides the specifications of
hardware for which all Java technology is compiled. This specification allows
the software in Java is platform-independent since the compilation is done
for a generic machine known as the Java Virtual Machine (JVM). This can
to be emulated by software in order to be executed on different systems
existing computer systems, or be implemented in hardware.
From the source code, the compiler generates bytecodes. These bytecodes are
machine code instructions for the JVM. Each Java interpreter has a
implementation of the JVM.
The JVM specification provides very concrete definitions for the
implementation of:
Characteristics of Java
Robust:
Java performs checks for issues both at compile time
like at runtime. At compile time, there is no mystery because
all languages perform those checks, however, at runtime,
the JVM, which performs the interpretation of bytecodes, detects when there is any
problem in the execution of the program, and throws exceptions that can be caught
by the programmer with the purpose of recovering from such errors.
Neutral architecture (multiplatform):
Thanks to the compilation being done to an object code independent of the
architecture of the machine (bytecodes), we only need to use the interpreter
suitable for our program to work on any platform. The motto of
It is 'write once, run anywhere'.
Sure:
Campus Empower Yourself | info@[Link]
Since all execution is carried out by the JVM, Java programs can be subjected to
many checks before being executed on the machine. Specifically:
• The code is passed through a ByteCode checker that verifies the
format of the code snippets and detect illegal code snippets
(code that falsifies pointers, violates access rights over objects, etc.).
• The class loader separates the namespace from the local file system.
from the resources coming from the network. This limits any application of the
like Trojan Horse, since the classes are first sought among the locals and
then between those from abroad.
• Regarding the security of the source code, the JDK itself provides a
Bytecode disassembler, which makes any program able to be
converted to source code from its bytecodes. Using javap I don't know
it obtains the original source code, although it disassembles the program showing its
structure. This source code security issue is still something
pending to rectify.
Portable
Beyond basic portability due to its architecture independence, Java
implement other portability standards to facilitate development.
Integers are 32 bits in two's complement.
Java builds its user interfaces through an abstract windowing system.
so that they can be implemented in UNIX, Mac, or PC environments.
Development with Java:
To be able to develop software with Java, we need a series of tools that
provided to us by Sun through its JDK (Java Development Kit).
Just like the natural language we use to communicate, whether orally
In writing, any programming language has elements and rules.
what must be known when programming.
The elements of natural language allow us to designate things (names), to express
qualities of those things (adjectives), express actions (verbs), etc.
The syntactic (structure) and semantic (meaning) rules allow for understanding.
among the elements that make up communication.
In programming languages, we also find syntactic rules that
we must respect when creating the programs and a semantics in charge
to solve the problem we want to program.
Elements and syntactic rules of programming languages:
Although all the concepts that we will learn next appear in all the
programming languages have differences in the implementation of each one
they require an individual study for each of them.
Comments on the programs:
Campus Boost Yourself | info@[Link]
An important aspect when creating a program is to comment as much as possible.
as detailed as possible what each of the commands that are part of the
program, with the purpose of being able to remember in the future the function that each performs
one of them, and facilitate its study for people outside the program.
Identifiers:
In every programming language, the need arises to use a series of elements.
that we should designate with some name, for example:
ELEMENT
Variables Elements used to reference memory positions where
we will be able to store necessary data for the program.
Functions - Elements used to reference memory positions where
Here is the program code.
Objects Elements that encapsulate variables (properties) and functions
(methods) in such a way that it becomes easier to model the problems
what we want to solve by simplifying program design
complex
etc. As we progress, we will get to know more elements of the
programming languages.
When assigning names to all these elements, some rules must be followed.
Basic data types:
The simplest mental model that can be had of a computer application is the
from a black box that receives input data, processes it, and delivers output data
represented in some way.
These input data, which must be stored in memory and referenced
through some variable, they can be of different nature (numerical,
alphanumeric, etc.).
Each programming language has some basic data types to which
we have to adapt when carrying out the analysis of the data we need
in our application.
Variables:
This element plays a very important role in the program because it is the mechanism
that puts at our disposal the programming language to manage a
simple way the application data.
When declaring a variable in the program, we are reserving a memory area for
subsequently host a data. There are languages that require us to specify
the type of data to be stored (java) and others that do not need it (javascript).
By assigning a value to the variable, what we are doing is storing the data in the
memory position that was reserved for that variable.
Campus Impulse | info@[Link]
At all times we must keep in mind that by using the variable we are actually
using the data it represents.
Operators:
One of the first applications of computers was mathematical calculation and,
even though it has now taken a back seat, programming languages offer
a series of elements that allow performing operations with the data.
These operations are not limited to arithmetic operations. We also have
of logical operations, comparisons, etc.
Control statements:
However, the feature that gives the computer its power is the ability to
processing of the one available.
Although this may scare us, the type of processing it can perform is very
basic, limited to:
Making decisions about whether or not to execute certain tasks based on the
compliance or non-compliance with one or several conditions (decision statements). In those
conditions will always involve data (or if you prefer, their representatives)
variables).
Change the normal execution flow of the program code (jump statements or
loops). These alterations will also be controlled by variables.
The appropriate combination of this type of statements is what will define the structure that
solves a certain problem.
Data storage using Arrays:
We have seen the use of variables as a basic mechanism to store and access
data in memory. However, in most applications this type of
information storage falls short for being too simple and
we need more complex storage systems, but also more
powerful.
One of these systems, which appears in all programming languages, is that of
the Arrays.
Exceptions:
All programming languages notify us of the errors we make in real time.
of compilation, but few are those that have been designed to continue notifying about
possible runtime errors. Java applications, thanks to their
executed under the supervision of the virtual machine (JVM), are being controlled
constantly. In case an execution error occurs, an exception is thrown.
which can be collected and processed by the programmer in their application. In this way,
what used to end in an abnormal program termination, with java can be
resolved.
Campus Boost Yourself | info@[Link]
Objects:
Java is an object-oriented programming language. The importance of this topic
it is such that we dedicate the entire following chapter to it.
1.2. Classes
The different programming technologies differ in the way they offer
structure the data and the code that make up an application.
When it comes to presenting the analysis of the problem to be solved by software, all
technologies have chosen to divide this problem into smaller parts.
the strategy to follow is to achieve a structure in which each of those parts performs
a unique and indivisible task, coordinated by a main part that obtains the
Information about what to do with your interaction with the user. Currently
this interaction is carried out through a graphical environment and the commands are generated
through events.
In procedural, function-oriented languages, the structure is implemented
taking the code as a reference. Each part is called a subroutine,
procedure or function depending on the language we are in, each one
it runs taking into account only the input parameters without modifying anything external
to her.
In imperative, object-oriented languages, the structure is created by taking
how to reference the data. The data is grouped according to its nature in
components called objects. To define what data an object can contain and
we use a template that we call class which defines its properties
(data) and methods (actions).
An object, like in real life, has a series of properties. For example, let's say
we want to create a system to store and organize urban planning files
work. On paper, a file contains the person's data and information related to
your request. Such a person may be associated with a series of data such as name,
last names, ID number, address, phone number, etc.
For the design of a system, we must identify the data and group them into objects.
We also need to identify what actions an object can perform and how they affect.
to others. In this example, we started from a dataset of a form to
divide them into two objects each responsible for managing said data. As we have
commented a class defines an object, in this the name of each property is indicated
and what type they are, such as text, numeric, or another object like in this case the
applicant person. It is also defined what actions they perform and these can be modified
the data of said class.
A class is an entity that determines how an object will behave and what it will contain.
the object. In other words, it is a plan or a set of instructions for building a
specific type of object.
Campus Impulse | info@[Link]
1.3. Creation of a class.
In Java, a class is usually represented with the following structure:
public class ClassName
{
// This is a comment
/*
This is a comment with multiple lines
*/
Property definition --> Characteristics of the element that
we describe with the class.
public int publicProperty; // <- Can be accessed by anyone
private int privateProperty; //<- Only the class can access
protected int protectedProperty; //<- The class and those that inherit
about her
static int protectedProperty; //<- Static property accessible
by anyone
// Definition of the methods --> Behavior and functionalities
of the element.
public void doSomething() {//<- public function that returns nothing
//function code
}
public int returnsSomething() { //<- public function that returns a
whole
return [Link]; //We return a property
}
As can be seen in Java, classes are defined with the word class followed by the
name by which we want to identify it. We are going to explain a series of words
used alongside properties and methods, these control how access is granted to
the property that accompanies:
• public: indicates that the property is accessible from outside, for example we can
access properties of an object from class methods but also
from outside the class using the object variable and a dot, for example
[Link].
Campus Get Inspired | info@[Link]
• protected: this is related to object inheritance, a class that inherits
Another can access that property, but not from outside the parent class.
• private: properties with private are only accessible from the class in which
it is defined, they cannot access inherited classes either from outside.
• static: it is a property shared among all objects created from
the class is also accessible through the class itself without requiring an object.
It can be used alongside public, protected, and private.
• final: the property cannot be altered, in the case of a primitive type the value
it cannot change, however, it does have a reference to an object that can
it can be changed, but it will not be allowed to change the reference to another object. It
can be used together with public, protected, and private.
A method or also called a function is defined similarly to properties,
it has limitations in access and can even be static, depending on the value or object that
return is indicated with a name prior to that of the function, in case they do not return
nothing is indicated with void.
It should be borne in mind that the variable of an object is not the object itself, but a
reference, in case a function returns a private property by reference to
an object we risk that later the object may be modified and said
modifications unexpectedly affect the functioning of others
components. To prevent the modification of an object referenced by a property
a copy of said object must be made and returned, in this way any
Modification made outside of the class will not interfere.
In the previous code segment, we have made use of primitive data and types.
In Java, every variable has a defined type. A type can be understood as a
identification of what data the variable has, a variable can refer to a
object for which its type is the name of that class. However, there are not only objects
In Java, a variable can also hold a value of a specific type, these types
we call them primitives. Java includes eight primitive types:
• byte: is an integer that occupies 8 bits in memory. Its values range from -128
a 127.
• short: it is a 16-bit integer. Its minimum value is -32,768 and the maximum is 32,767.
• int: it is a 32-bit integer. Its minimum value is -2,147,483,648 and the maximum
2,147,483,647 (inclusive). It is the most commonly used type for integers unless
that there is a reason to use another one, such as memory savings.
• long: it is a 64-bit integer. Its value ranges from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807. It is obviously used when int does not reach the value
what is required.
• float: it is a single-precision floating-point data. We will not go into detail.
about how it works, but it is used to store decimal values that do not
They require great precision as they can produce a certain degree of error.
in the decimal part.
• double: 64-bit floating-point data with double precision. Similar to float but
it admits a greater range of values, it is commonly used when dealing with values
decimals.
• boolean: it only has two possible values true (true) and false (false).
• char: contains a single 16-bit Unicode character.
Campus Launch Yourself | info@[Link]
Java is considered a strongly typed language because it requires specifying the type of
each variable, in the case of other languages like PHP you can use types, but it is not
mandatory. Although it may imply an additional workload depending on the situation
the use of types helps to prevent errors.
In the following example we can see a complete Java file that contains the
definition of a class, the defined class is named Car:
import [Link];
import [Link];
import [Link];
public class Car {
private boolean state = false;
private int speed = 0;
public final static int VMAXIMA = 120;
public static void menu() {
1.- Get in the car
[Link]("2.- Start");
3.- Stop
4.- Exit the car
[Link]("",");
[Link]("Enter an option");
public void mount() {
if(estado == false) {
You are already on top of the car.
estado =true;
}
else{
You were already up, don't try to go up again
time.
}
menu();
}
public void start() {
if(estado == false) {
First get in the car
}
else if(speed == MAXSPEED) {
You can no longer accelerate any more
}
else{
++speed;
Impúlsate Campus | info@[Link]
[Link]("Current speed= " + speed);
}
menu();
}
public void stop() {
if(speed == 0) {
[Link]("If you are stopped because you brake");
}
else{
The braking is done suddenly
velocidad =0;
}
menu();
public void exitCar() {
if (status == false) {
You haven't gotten on and you're already getting off
}
else if(speed != 0) {
First brake and then go down
}
else{
You just got out of the car.
}
menu();
}
public int getSpeed(){
return [Link];
}
public void setVelocidad(int v) {
if([Link] > v){
[Link] = v;
}
else{
[Link] = v;
}
}
}
Campus Impúlsate | info@[Link]
As can be observed, there is a property called VMAXIMA set as public,
static and final this means that it can be accessed from outside the class, this
shared among all instances and its value is final, that is, it cannot be
modified. We understand that the maximum speed is the speed limit that all the
Car instances support. We are not interested in exceeding the maximum speed.
established in the vehicle, which we declare private and to modify it for
Anyone outside our class must go through the setVelocity function.
In the previous segment of code, the import statement has been used. Before
nothing, let's explain what a package is in Java:
In Java, a package is known as a set of classes and other packages.
they follow a hierarchical folder structure. In the following image, you can see the
directory of a package called 'ssh_tunnel' which in turn contains a package
named 'utils'. Typically, classes of the same type are grouped in a package.
application, organization, system or that share a series of similar functions.
(Figure 1).
Figure 1 The image shows a screenshot of a Java package with class files and a directory.
what does a subpackage represent
To use classes from external packages, we need to use their name.
In a statement, if it is a one-time use, we can use the name of the package.
followed by the class as seen in the following example:
[Link] orange = new [Link]();//Using
the full name
import [Link]; // we import the Lemon class
import [Link].*; // we import everything
Campus Empower Yourself | info@[Link]
1.4. Objects
In software engineering, SOLID (Single responsibility, Open-closed, Liskov
substitution, Interface segregation, and Dependency inversion) is an acronym
mnemonic introduced by Robert C. Martin in the early 2000s that
they represent five basic principles of object-oriented programming and design.
When these principles are applied as a set, it is more likely that a
developer creates a system that over time is easy to maintain and
expand. The SOLID principles are guidelines we can use in the development of a
software that will help us eliminate dirty code causing the programmer
You have to refactor the source code until it is readable. It should be used in
test-driven development or TDD, and it is also part of the global strategy of
agile software development and adaptive software development.
The single responsibility principle indicates that each module or class should have a
responsibility for only part of the functionality of the software and this
responsibility must be encapsulated in its entirety by the class. All its
services must be closely aligned with that responsibility. Robert C.
Martin expresses this principle as follows: A class should have only one reason.
to change.
The open/closed principle states that 'a software entity (class, module,
function, etc.) must remain open for extension but closed for modification
modification. In other words, it should be possible to expand the behavior of the
entity without having to modify its source code.
open/closed is used in two ways: both are based on inheritance in order to
to resolve the apparent dilemma, but both their objects, techniques, and results are
different.
The Liskov substitution principle is a principle of object-oriented programming.
It can be defined as: It is possible to use as its parent any class that inherits from another.
without the need to know the differences between them.
In a more formal language: if S is a subtype of T, then all objects of type T
In a program, they can be replaced by objects of type S (in other words, the
objects of type S can substitute for those of type T), without changing any of the
desirable properties of the program (such as correctness, the task it performs,
etc.) In a more formal way, the Liskov Substitution Principle (LSP) defines
a particular way a relationship of subtyping, known as typing of
behavior, which was initially introduced by Barbara Liskov in a
conference back in 1987 called "The Abstraction of Data and Hierarchy." It is
more related to a semantic type of relationship than to a syntactic type, since so
it only aims to ensure the semantic interoperability of types within
a hierarchy, the types of objects in particular. Jeannette Wing and Liskov created the
jointly in an article in 1994 that states the following:
SeaΦ( ) a verifiable property about the objectives of type so
Φ( ) it must be true for the objectsyof the type where it is a subtype of
Campus Empower Yourself | info@[Link]
The Interface Segregation Principle (ISP) states that
clients of a given program should only be aware of those methods that
they really use, and not those who do not need to use. The ISP is applied to an interface
broad and complex so that it can be sectioned into smaller and more specific ones, in such a way
way that the customer only uses the one they need, thus being able to ignore the rest. To this
reduced type of interfaces are called 'role interfaces'.
The ISP was conceived to keep a system decoupled from other systems.
those that depend on it, and that makes it easier to refactor, modify it and
redeploy it. ISP is one of the five S.O.L.I.D. principles of Object-Oriented Design
Objects, similar to the High Cohesion Principle of GRASP.
The dependency inversion principle consists of the following two points:
A: High-level modules should not depend on low-level modules. The two
They should depend on abstractions.
B: No abstraction should depend on any detail. It is the details themselves.
details that should depend on the abstractions.
In the object-oriented paradigm, it is most common to have a hierarchy of
defined objects, because the higher-level objects are the ones that usually include those of
low level.
A forest contains trees, which in turn contain leaves, which contain cells...
That is why the word "investment" was chosen, because it breaks with this dynamic.
The initial intention is that there should be no need for dependency between
some modules and others, but depend on abstractions. In this way, our
modules can be more easily reusable.
As we have already seen, an object is an abstract representation composed of
properties also called attributes and a series of methods or functions to
manipulate said properties.
We can consider Classes as object templates, they define what properties
they have and their methods, instantiating a class results in a new object. In Java
the properties of an object can be of primitive type or references to other objects,
regarding this last point, we understand that an object can be composed of others,
for example, a bicycle is composed of a pedal, handlebars, wheels, etc. Each
An object of a class can have its own value in each property, although they share
the same functionality, each chair can be of a different color but the fact that
It serves to sit, it doesn't change.
Creating an object in Java is simple:
A red car with five seats
Car myCar = new Car("red", 5);
Campus Impúlsate | info@[Link]
We declare a variable with the name of the class as the type and the instance with new. When
Doing this reserves memory for the object and the variable references it.
case of carrying out:
Am I copying the object?
Car myOwnCar = myCar;
What we do is assign the same object to the variables myCar and myOwnCar,
Any modification like [Link]("blue") will affect both. If what
we want a copy there are some solutions in third-party libraries, but the most
It is certain that the developer implements their own function to create duplicates. By
example, through the clone method or a constructor with an object of the same class
as a parameter and copy the primitives, for properties that are references to objects
They would also need to be duplicated:
public class Car {
//.....
publicCar(Car original){
[Link]=[Link];
[Link]=[Link];
//......
}
public Car clone() {
I have already created a copy constructor, I can save myself
repeat the code
NewCar=new Car(this);
returnnew;
}
Throughout the module, we will see the use of objects defined by the String class, this is
a class defined in Java that allows storing and working with strings of text. The
the peculiarity of this class is that it does not allow modification of the text it stores,
methods like split create an array with two new instances of String each with
a copy of a fragment of the original text. Therefore, there is no need to worry about
generate copies of private properties of this object since by design it prevents its
alteration. The text enclosed in double quotes is considered by the compiler of
Java as a String object.
If you are not familiar with the concept of array in Java, it is a container of objects.
that is to say, it stores a fixed number of objects of a specific type. Its capacity is defined
when created:
Car[]referenceArray;
memory for 15 cars
referenceArray=newCar[15];
Impúlsate Campus | info@[Link]
1.5. Practical Example with Objects.
Next, we will show a practical example of creating a basic program in Java.
It will be necessary to have some Java development kit installed, you can find it
entering the word JDK (Java Development Kit) in any search engine. The JDK
contains the necessary tools for compiling the source code and its
execution. The included compiler is developed to be used through a terminal,
In this case, we will use the Windows command console (CMD) and the command
denominator.
Make sure to download the appropriate version of the JDK for your processor and system
operational, previously accepting the terms of the license. Once downloaded the
installation continues like any other installer. (Download the JDKhere).
Figure 2 shows part of the download page for the Java development kit indicating that it must be accepted.
the terms of use and download the appropriate version for the processor architecture and operating system, in this
case Windows 64 bits.
As explained, to create an object we need a template.
called class. Each class defines what properties an object can have and its
methods.
Each class is assigned a name to identify it and use it during development.
from an application, in the following example we have the Invoice class, the creation of a
an object created from a class is called instantiation, every object created from
We would call it an instance of Invoice.
Let's show an example of a class and its utilization. We will create a new class.
Invoice call. An invoice consists of a holder's name, a concept, a
price, the VAT and the total of the invoice.
Campus Impúlsate | info@[Link]
public class Invoice {
public String AccountHolderName;
public String InvoiceConcept;
public double price;
public double Total;
public double Iva;
}
We have created a class in which we can store a series of primitive data.
its set. This class contains a series of members that will store each object.
created from the Invoice class. In the example, we can observe variables of type
String is a class included in Java to represent a text string.
text is immutable, meaning it cannot be altered, which is why the String class implements a
a series of methods for operations such as text concatenation and division that
they return new instances.
Each Invoice object, that is, each instance of the class, has its own copy of the
member variables. As we mentioned, the variables specific to a class
(properties) can be of primitive types (boolean, int, long, double...) or references
to objects of another class (composition).
Campus Impúlsate | info@[Link]
In our example, we have created five member variables of the invoice class, namely
Member variables are elements that belong to the Invoice class and can only be
used by objects of the Invoice class. Each Invoice that we create will have some
different values for each member.
public class UtilizationInvoice {
public static void main(String[] args) {
Invoice f1=newInvoice();
Adrian Ramos
IPad
[Link]=540;
[Link]=30;
[Link]=570
[Link]("Invoice data number 1");
[Link]("Holder Name: " + [Link]);
[Link]("Invoice Concept: " + [Link]);
[Link]("Price: " + [Link]);
[Link]("Iva: " + [Link]);
[Link]("Total: " + [Link]);
[Link]("-------------------------------------");
Invoice f2=newInvoice();
Lucia Serrano
PSP
[Link]=169;
[Link]=15;
[Link]=184;
[Link]("Invoice data number 2");
[Link]("Holder Name: " + [Link]);
[Link]("Invoice Concept: " + [Link]);
[Link]("Price: " + [Link]);
Iva:
[Link]("Total: " + [Link]);
}
}
In this example, we show another class called UtilizationInvoice, this class
it has not been created for the purpose of creating objects but for the execution of code, which is
content in the method domain.
As we can verify, each referenced object of the invoice class contains some
different data for each element. That is, each member of the Invoice instance
store different data in each object.
To compile the program, we start from two files with a .java extension, it is important
use a plain text editor like Notepad or Notepad++. Each file must
to have the name of the class, in this example it should result as: [Link]
Campus Impúlsate | info@[Link]
[Link]. For greater ease, we have created them in a folder in
the unit C:\, to compile our program we use the command javac (Figure 3):
Figure 3 Simple example of the javac command for compiling .java files javac *.java
If you have compiled it, you will have noticed a small typo in our code,
to be precise on line 9 of [Link] where it says '[Link]'
= 570" a semicolon is missing at the end (Figure 4):
Figure 4 Example of a syntax error shown by the javac command. In this case, line 9 of
[Link] is missing a semicolon at the end.
In the shown command, we compile all the *.java files in the folder by giving
as a result [Link] that contain the bytecode of each class, for
to run our program we must use the name of the class that contains the
functionmain(Figure 5):
Figure 5 shows the execution of a program compiled by javac with the command java -cp . UtilizacionFactura.
Print on screen the data of two different invoice objects.
As we mentioned, each Invoice object had its own content and this has been
printed ([Link]) in the program output.
Campus Impúlsate | info@[Link]
1.6. Practical Example with Objects II.
To refer to the objects that belong to the class we are on
writing uses the word clavethis. This word refers to any
element declared in the class.
public class Invoice
{
public String HolderName;
InvoiceConcept
public double Price;
public double Total;
public double Iva;
INVOICE BUILDER
publicInvoice()
{
Let's initialize the class members
without holder
no concept
[Link]=0.0;
[Link]=0.0;
[Link]=0.0;
}
}
We can observe a method with the same name as the Factura class. This method
we call it a constructor and it will be called every time an object is created (instantiated),
its main function is to assign a value to each variable, this may include new ones.
instances of other classes.
If we now use an object of the Invoice class, by simply instantiating an object, the
Initial values have been created from the constructor.
public class InvoiceUtilization
{
public static void main(String[] args)
{
Invoice f1=newInvoice();
[Link]("Invoice data BUILT");
[Link]("Account Holder Name: " + [Link]);
[Link]("Invoice Concept: " +
[Link]);
[Link]("Price: " + [Link]);
[Link]("Iva: " + [Link]);
[Link]("Total: " + [Link]);
}
}
Campus Impúlsate | info@[Link]
As can be observed, instantiation is done using the new instruction followed by
of the class name and some parameters. In this case, the constructor does not receive any.
As a result of the execution, we see the initial values created from the constructor.
(Figure 6):
Figure 6
[Link] between the elements
Objects intervene in the behavior of the system by interacting with others,
for example, in a car an object pedal interacts with the object brake, this
produce calling a public method that the pedal object offers to carry out
This action results in a reduction of speed in the car object.
Aside from defining objects, we are also defining their relationships; an object delegates.
a job to another that can be part of you or another of the system.
As we have seen, a set of properties or methods can be defined in an object.
public access, we call that set the public part or interface of the object.
Other objects do not need to know how others carry out their operations, only
that calling a public method produces a result. ( See diagram in Figure
7).
Figure 7 Representation of the public methods of an object connected to the internal implementation.
Campus Boost Yourself | info@[Link]
For the development of an application that interacts with the user, the basic strategy
to follow is to achieve a structure in which each of the parts performs a task
unique and indivisible. Each component would be coordinated by a main one that obtains
information through its interaction with the user. Currently, this interaction
It is carried out through a graphical environment and commands are generated by events.
For the development of a system, it is important to decide in advance how they interact.
objects besides their data and responsibilities. It is a good idea to keep in mind
that for many cases, solutions have already been implemented that are considered optimal or those
more appropriate. This is why the concept of software design patterns was born.
Simplifying, a pattern describes a generic problem and its solution, a pattern does not have
why be a fixed solution, but it helps to understand how to organize a system to
that its parts interact in the best possible way.
As an example, we have a representation of the design pattern in the following image.
Model-View-Controller (MVC), this pattern arises from the need to separate the
data and the business logic of the user interface. The class that takes on the role of
the controller receives notifications from the view about its interaction with the user, such as
for example, pressing a specific button or entering text. When the
the controller is notified about an action, makes changes to the model, this
is responsible for storing the data and the changes are sent to the view.
Figure 8 Diagram of the Model-View-Controller design pattern. This image represents the interaction between the
Main components of an application that interacts with the user following the MVC design pattern.
For example, we can have a screen with a person's data and buttons for
Next, Previous and Save. The representation of the data and the interaction with the
the actions are carried out by the interface. The user presses the next button and the
Campus Empower Yourself | info@[Link]
the controller is notified, then it makes the next bicycle the selected one in
the model and therefore the view is notified with the new information that will be displayed.
1.8. Example Interaction between elements.
Let's open a notebook and write the code for our first class.
We must remember that Java is a 'Case Sensitive' programming language, that is to say,
difference between uppercase and lowercase, so we will write literally the
content of our first example in the notepad.
Next, we are going to save each file with our notepad with the name
of the class followed by the extension '.java' in the location we are going to test.
our examples. It is advisable to create a folder to be able to locate everything
our practices. We can use any other text editor, but it is
essential that it only stores plain text, text editors would not be useful for us
Word or WordPad style, since they store more information besides the written text,
an example of these editors could be UltraEdit or some 'free' notepad that
found on the internet and that have more features than traditional notepad
from Windows.
[Link]:
public class Writer{
//Private part
privateString partText1;
privateString partText2;
private int times;
privateStringwrite(){
If there is no other variable with the same name, this is not
necessary
The String class has a static method to produce a
string from other types
String vecesString = [Link](veces);
returnpartText1+times+partText2;
}
Public part, interface to the outside
publicWriter(){
In a place in La Mancha whose name
I don't want to remember by ";
first time
[Link]=0;
}
In this case, we send the reader a text through one
of his methods
public void sendMeText(Reader reader) {
[Link]++; //We increment it
[Link]([Link]());
}
}
Campus Impúlsate | info@[Link]
[Link]:
public class Lector {
public int num;
public void askTheWriter(Writer writer) {
[Link](this);//We pass the object itself
}
public void send(String text) {
[Link]("I am reader number " + [Link](num));
and I have received
}
}
[Link]:
public class Main {
public static void main(String[] args) {
Reader lector1 = new Reader();
Reader lector2=newReader();
[Link]=1;
[Link]=2;
Writer cervantes=newWriter();
[Link](cervantes);
[Link](cervantes);
[Link](cervantes);
}
}
We must ensure that the name of our file "java" must be the same.
name that our class, including the differentiation of uppercase and lowercase, in
In our example, we have [Link], [Link], and [Link].
I am going to create a folder in the C:\Example2 and I will store the practices there.
location. In the notepad we will select as Type: "All files" and
we will write the extension ".java" for our first class.
We have compiled the files with the command 'javac *.java', and then it
We run with the command 'java -cp . Main', keep in mind the name of the class.
What does the main function contain as shown in the image:
Campus Impúlsate | info@[Link]
Figure 9 We show the result of two objects interacting with each other. Two readers request a writer to
write something and this responds.
As we can see, the Writer object in its private part keeps track of how many.
Sometimes they have requested a text from him and he responds in the reply mentioning what it is
1st, 2nd, and 3rd time. The reading object does not know this private part and is only interested in the request.
of text that it offers in its public part. In this case, the author also knows
to the reader, we do not use a function that returns the text, but rather call a function of the
reading object to respond.
Due to the simplicity of this example, we have used a simple text editor, if
It is also possible to use an IDE (Integrated Development Environment), which
provides functions such as syntax correction and compilation and execution from a
graphical interface. Examples of free or open-source IDEs are Eclipse or Netbeans.
Note
We can save the practices in any location, but it is convenient
save them in an easily accessible "path" since later we will have
that write said route in our Ms-Dos command window.
[Link] II
Inheritance
Before discussing interfaces, we must talk about the concept of inheritance in the
object-oriented paradigm.
Let's imagine that we have the instructions to build a specific chair with some
characteristics and concrete uses, now let's suppose we want to create a chair
based on the original design, but with some changes, such as some
reposamuñecas. Since we do not charge by the hour, we are not going to write any instructions.
from scratch since we have the original chair, we just copy the parts in
common of the original instructions and we add our part. This is an example
about the concept of object inheritance, we have defined a class and we want to create
a similar one, but with certain changes.
Campus Impúlsate | info@[Link]
By inheriting from a class, we can use the methods and properties defined.
protected or public by the parent class. From outside, the objects created from
the child class will be like the parent except for what we have added or
overwritten. (See diagram of Figure).
Figure 10 A diagram that simply shows the concept of inheritance. We have a common chair, from which
inherits a desk chair and one with armrests, and the latter in turn has one from which it inherits with
padded wrist rest.
In this example, we consider that a 'Office chair' is a child of 'Common chair'.
In addition to inheriting from a normal class, we have the concept of an abstract class.
it would be analogous to the abstract concept we have of a chair. Abstract classes do not
they can be instantiated, but they have a series of properties and methods common to
classes that use it as a parent. It is also possible to define abstract methods, so
they write like any other method, but without the code block enclosed in
brackets. Any class that inherits from another with abstract methods must
implement them.
Interfaces
Now that we know about inheritance, we can talk about the concept of interfaces.
An interface in Spanish is a set of abstract methods and
final properties in order to define the behavior of a class.
We can consider an interface as a 'contract' that a class must follow.
The difference between an interface and an abstract class is that the interface only defines that
constants must be implemented while an abstract class can
implement methods or define them as abstract, the similarity they share is that both do not
they can be instantiated.
Campus Impúlsate | info@[Link]
A class can only derive/inherit by extending a base class, but
You can implement multiple interfaces. The names of the interfaces are indicated.
separated by a comma after the word implements.
In Java, an interface is defined with the word interface followed by the name, it is also
Is it possible for an interface to inherit from another or multiple interfaces like a class would?
by extends:
In this example, we create an interface with the methods we want to have.
implement.
public interface CarInterface extends Vehicle {
intV_MAXIMA=120;
public void mount();
voidstart();
voidbajar();
intverVMaxima();
void changeVMaxima(int VMAXIMA);
voiddown();
void usar() throws IOException;
voidmenu();
}
As can be seen, we only use the public modifier in one of the functions, in
An interface is implicitly public, so it can be omitted.
In addition, all properties are considered public, static, and constant.
staticfinal), in the same way as functions, these can be omitted.
Implementation of the interface
If a class wants to implement an interface, it must use the keyword implements. If
we want to inherit and implement at the same time, we must place extends first
followed by the class name and then implements followed by the name of the
interface.
Syntax:
public class Macaroni extends Pasta implements Food,
Disposable,...
Class body
}
public abstract class Fruit implements Food {
//..............
}
Impulse Campus | info@[Link]
If a class implements an interface, we can use that interface as a type in the
variable of objects. For example, an Orange object that would inherit from Fruit (code
previously), can be assigned to a variable of type Food, said variable would be
limited by the functions and constants defined in the Food interface. For example,
We can have a class ShoppingBasket that contains a list of the Food type, from this
this way we can store and use objects based on an interface, even if they are
originally instances of different classes.
public class Orange implements Food {
//..............
}
public class Cookie implements Food {
//..............
}
public class ShoppingBasket{
privateArrayList<Food>foods;
//......................
public void meter(Element ali) {
[Link](ali);
}
}
Orange orange=newOrange();
Orange food As Food = orange; // From this variable it
consider food
Food cookie = new Cookie();
Cookie anotherCookie = new Cookie();
ShoppingCart cesta=newShoppingCart();
[Link](orange);
[Link](cookie);
[Link](otherCookie);
Campus Impúlsate | info@[Link]
1.10. Peculiarities of Java.
As we have seen, Java follows the object-oriented programming paradigm, but
that does not mean it can have characteristics of other paradigms like the
functional programming. For example, concepts were introduced in version 8
functional programming, aimed at providing better solutions when dealing with
large volumes of data. It should be noted that the new features in
the language is incompatible with earlier versions of the JVM.
For example, a function that adds one to each value in a list.
of integers
public List<Integer> addOne(List<Integer> numbers) { return
[Link]().map(number -> number + 1)
On the other hand, before explaining the process of creating a program, it is advisable
explain that in Java we will handle three types of applications:
• Text mode application: In this type of application, the interaction with the
User (data entry and presentation of results) is done in text mode.
(there will be no text boxes, buttons, ...). The mouse will not be used in these.
applications. They are the applications that we will carry out in the first block where
Our objective will be to learn the basics of Java. It is also
interesting when we create the prototypes of our programs due to
that debugging is easier.
• Graphic mode application: In this type of application, the interaction with the
The user does it in graphical mode. These applications can be of all types and
one should not think only about the Internet:
Word processor, databases, programming environment,
graph treatment...
• Mini-applications (applets): Small programs that cannot run independently.
independent form, but they need the support of a browser. These
programs are designed to be invoked from an HTML page,
they travel through the network and are executed on the client's machine.
Campus Impúlsate | info@[Link]