

























































Estude fácil! Tem muito documento disponível na Docsity
Ganhe pontos ajudando outros esrudantes ou compre um plano Premium
Prepare-se para as provas
Estude fácil! Tem muito documento disponível na Docsity
Prepare-se para as provas com trabalhos de outros alunos como você, aqui na Docsity
Encontra documentos específicos para os exames da tua universidade
Prepare-se com as videoaulas e exercícios resolvidos criados a partir da grade da sua Universidade
Responda perguntas de provas passadas e avalie sua preparação.
Ganhe pontos para baixar
Ganhe pontos ajudando outros esrudantes ou compre um plano Premium
An introduction to java programming for beginners, focusing on object-oriented concepts and using eclipse for development. Topics covered include java syntax, creating java objects, access specifiers, polymorphism, and using eclipse for java development.
Tipologia: Notas de estudo
1 / 65
Esta página não é visível na pré-visualização
Não perca as partes importantes!


























































Skill Level: Introductory
J Steven Perry ([email protected]) Principal Consultant Makoto Consulting Group, Inc.
19 Aug 2010
This two-part tutorial introduces the structure, syntax, and programming paradigm of the Java™ language and platform. You'll learn the Java syntax you are most likely to encounter professionally and Java programming idioms you can use to build robust, maintainable Java applications. In Part 1, J. Steven Perry guides you through the essentials of object-oriented programming on the Java platform, including fundamental Java syntax and its use. You'll get started with creating Java objects and adding behavior to them, and conclude with an introduction to the Java Collections Framework, with considerable ground covered in between.
Find out what to expect from this tutorial and how to get the most out of it.
The two-part "Introduction to Java programming" tutorial is intended to get software developers who are new to Java technology up and running with object-oriented programming (OOP) and real-world application development using the Java language and platform.
Java language basics Trademarks
This first part is a step-by-step introduction to OOP using the Java language. The tutorial begins with an overview of the Java platform and language and is followed by instructions for setting up a development environment consisting of a Java Development Kit (JDK) and the Eclipse IDE. Once you have been introduced to your development environment's components, you will begin learning basic Java syntax hands-on.
Part 2 covers more-advanced language features, including regular expressions, generics, I/O, and serialization. Programming examples in Part 2 build on the Person object that you begin developing in Part 1.
When you've finished Part 1, you will be familiar with basic Java language syntax and able to write simple Java programs. You should follow up with "Introduction to Java programming, Part 2: Constructs for real-world applications" to build on this foundation.
This tutorial is for software developers who are not yet experienced with Java code or the Java platform. The tutorial includes an overview of OOP concepts.
To complete the exercises in this tutorial, install and set up a development environment consisting of:
Download and installation instructions for both are included in the tutorial.
The recommended system configuration is:
developerWorks® ibm.com/developerWorks
Java language basics Trademarks
suitable for the CPU chipset the program will run on.
At run time, the JVM reads and interprets .class files and executes the program's instructions on the native hardware platform for which the JVM was written. The JVM interprets the bytecodes just as a CPU would interpret assembly-language instructions. The difference is that the JVM is a piece of software written specifically for a particular platform. The JVM is the heart of the Java language's "write-once, run-anywhere" principle. Your code can run on any chipset for which a suitable JVM implementation is available. JVMs are available for major platforms like Linux and Windows, and subsets of the Java language have been implemented in JVMs for mobile phones and hobbyist chips.
Rather than forcing you to keep up with memory allocation (or use a third-party library to do this), the Java platform provides memory management out of the box. When your Java application creates an object instance at run time, the JVM automatically allocates memory space for that object from the heap , which is a pool of memory set aside for your program to use. The Java garbage collector runs in the background, keeping track of which objects the application no longer needs and reclaiming memory from them. This approach to memory handling is called implicit memory management because it doesn't require you to write any memory-handling code. Garbage collection is one of the essential features of Java platform performance.
When you download a Java Development Kit (JDK), you get — in addition to the compiler and other tools — a complete class library of prebuilt utilities that help you accomplish just about any task common to application development. The best way to get an idea of the scope of the JDK packages and libraries is to check out the JDK API documentation (see Resources).
The Java Runtime Environment (JRE; also known as the Java runtime) includes the JVM, code libraries, and components that are necessary for running programs written in the Java language. It is available for multiple platforms. You can freely redistribute the JRE with your applications, according to the terms of the JRE license, to give the application's users a platform on which to run your software. The
developerWorks® ibm.com/developerWorks
Java language basics Trademarks
JRE is included in the JDK.
Section 3. Setting up your Java development
environment
In this section, you'll get instructions for downloading and installing JDK 6 and the current release of the Eclipse IDE, and for setting up your Eclipse development environment.
If you already have the JDK and Eclipse IDE installed, you may want to skip to the Getting started with Eclipse section or to the one after that, Object-oriented programming concepts.
The JDK includes a set of command-line tools for compiling and running your Java code, including a complete copy of the JRE. Although you certainly can use these tools to develop your applications, most developers appreciate the additional functionality, task management, and visual interface of an IDE.
Eclipse is a popular open source IDE for Java development. It handles basic tasks, such as code compilation and setting up a debugging environment, so that you can focus on writing and testing code. In addition, you can use Eclipse to organize source code files into projects, compile and test those projects, and store project files in any number of source repositories. You need an installed JDK in order to use Eclipse for Java development.
Follow these steps to download and install JDK 6:
ibm.com/developerWorks developerWorks®
Java language basics Trademarks
executable for your platform).
ibm.com/developerWorks developerWorks®
Java language basics Trademarks
Eclipse is now set up and ready for you to create projects and compile and run Java code. The next section will familiarize you with Eclipse.
Section 4. Getting started with Eclipse
Eclipse is not just an IDE, it is an entire development ecosystem. This section is a brief hands-on introduction to using Eclipse for Java development. See Resources if you want to learn more about Eclipse.
The Eclipse development environment has four main components:
The primary unit of organization in Eclipse is the workspace. A workspace contains all of your projects. A perspective is a way of looking at each project (hence the name), and within a perspective are one or more views.
Figure 2 shows the Java perspective, which is the default perspective for Eclipse. You should see this perspective when you start up Eclipse.
Figure 2. Eclipse Java perspective
developerWorks® ibm.com/developerWorks
Java language basics Trademarks
developerWorks® ibm.com/developerWorks
Java language basics Trademarks
You have now created a new Eclipse Java project and source folder. Your development environment is ready for action. However, an understanding of the OOP paradigm — covered in this tutorial's next two sections — is essential. If you are familiar with OOP concepts and principles, you might want to skip to Getting started with the Java language.
Section 5. Object-oriented programming concepts
The Java language is (mostly) object-oriented. If you haven't used an object-oriented language before, its concepts might seem strange at first. This section is a short introduction to OOP language concepts, using structured programming as a point of contrast.
Structured programming languages like C and COBOL follow a very different programming paradigm from object-oriented ones. The structured-programming paradigm is highly data-oriented, which means that you have data structures on one hand, and then program instructions that act on that data. Object-oriented languages like the Java language combine data and program instructions into objects.
An object is a self-contained entity that contains attributes and behavior, and nothing more. Rather than having a data structure with fields (attributes) and passing that structure around to all of the program logic that acts on it (behavior), in an object-oriented language, data and program logic are combined. This combination can occur at vastly different levels of granularity, from fine-grained objects like a Number, to coarse-grained objects such as a FundsTransfer service in a large banking application.
A parent object is one that serves as the structural basis for deriving more-complex child objects. A child object looks like its parent but is more specialized. The object-oriented paradigm allows you to reuse the common attributes and behavior of the parent object, adding to its child objects attributes and behavior that differ. (You'll learn more about inheritance in the next section of this tutorial.)
ibm.com/developerWorks developerWorks®
Java language basics Trademarks
this list is a good start.
Behavior
An actual person can do all sorts of things, but object behaviors usually relate to some kind of application context. In a business-application context, for instance, you might want to ask your Person object, "What is your age?" In response, Person would tell you the value of its Age attribute.
More-complex logic could be hidden inside of the Person object, but for now suppose that Person has the behavior of answering these questions:
State is an important concept in OOP. An object's state is represented at any moment in time by the value of its attributes.
In the case of Person, its state is defined by attributes such as name, age, height, and weight. If you wanted to present a list of several of those attributes, you might do so using a String class, which I'll talk more about later in the tutorial.
Together, the concepts of state and string allow you to say to Person: tell me who you are by giving me a listing (or String) of your attributes.
Section 6. Principles of OOP
If you come from a structured-programming background, the OOP value proposition might not be clear yet. After all, the attributes of a person and any logic to retrieve (and convert) their values could be written in C or COBOL. This section clarifies the benefits of the OOP paradigm by explaining its defining principles: encapsulation , inheritance , and polymorphism.
ibm.com/developerWorks developerWorks®
Java language basics Trademarks
Recall that an object is above all discrete, or self-contained. This is the principle of encapsulation at work. Hiding is another term that is sometimes used to express the self-contained, protected nature of objects.
Regardless of terminology, what's important is that the object maintains a boundary between its state and behavior, and the outside world. Like objects in the real world, objects used in computer programming have various types of relationships with different categories of objects in the applications that use them.
On the Java platform, you can use access specifiers (which I'll introduce later in the tutorial) to vary the nature of object relationships from public to private. Public access is wide open, whereas private access means the object's attributes are accessible only within the object itself.
The public/private boundary enforces the object-oriented principle of encapsulation. On the Java platform, you can vary the strength of that boundary on an object-by-object basis, depending on a system of trust. Encapsulation is a powerful feature of the Java language.
In structured programming, it is common to copy a structure, give it a new name, and add or modify the attributes that make the new entity (such as an Account record) different from its original source. Over time, this approach generates a great deal of duplicated code, which can create maintenance issues.
OOP introduces the concept of inheritance , whereby specialized objects — without additional code — can "copy" the attributes and behavior of the source objects they specialize. If some of those attributes or behaviors need to change, then you simply override them. You only change what you need to change in order to create specialized objects. As you know from the Object-oriented programming concepts section, the source object is called the parent , and the new specialization is called the child.
Inheritance at work
Suppose you are writing a human-resources application and want to use the Person object as the basis for a new object called Employee. Being the child of Person, Employee would have all of the attributes of a Person object, along with additional ones, such as:
developerWorks® ibm.com/developerWorks
Java language basics Trademarks
It would be impossible to introduce the entire Java language syntax in a single tutorial. The remainder of Part 1 focuses on the basics of the language, leaving you with enough knowledge and practice to write simple programs. OOP is all about objects, so this section starts with two topics specifically related to how the Java language handles them: reserved words and the structure of a Java object.
Like any programming language, the Java language designates certain words that the compiler recognizes as special, and as such you are not allowed to use them for naming your Java constructs. The list of reserved words is surprisingly short:
developerWorks® ibm.com/developerWorks
Java language basics Trademarks
ibm.com/developerWorks developerWorks®
Java language basics Trademarks
Comments in code
Notice that Listing 1 also includes some comment lines:
// This is a comment /* This is a comment too / / This is a multiline comment */
Just about every programming language allows the programmer to add comments to help document the code. Java syntax allows for both single-line and multiline comments. A single-line comment must be contained on one line, although you can use adjacent single-line comments to form a block. A multiline comment begins with /*, must be terminated with */, and can span any number of lines.
You'll learn more about comments when you get to this tutorial's Writing good Java code section.
The Java language lets you choose the names for your objects, such as Account, Person, or LizardMan. At times, you may end up using the same name to express two slightly different concepts. This is called a name collision , and it happens frequently. The Java language uses packages to resolve these conflicts.
A Java package is a mechanism for providing a namespace: an encapsulated area in which names are unique, but outside of which they might not be. To identify a construct uniquely, you must fully qualify it by including its namespace.
Packages also give you a nice way to build more complex applications into discrete units of functionality.
Package definition
To define a package, you use the package keyword followed by a legal package name, terminated with a semicolon. Often package names are separated by dots, and follow this de facto scheme:
package orgType. orgName. appName. compName ;
This package definition breaks down like so:
ibm.com/developerWorks developerWorks®
Java language basics Trademarks
The Java language doesn't force you to follow this package convention. In fact, you don't need to specify a package at all, in which case all of your objects must have unique class names and will reside in the default package. As a best practice, I recommend that you define all of your Java classes in packages. You'll follow that convention throughout this tutorial.
Up next in the object definition (referring back to Listing 1) is the import statement. An import statement tells the Java compiler where to find classes you reference inside of your code. Any nontrivial object uses other objects for some functionality, and the import statement is how you tell the Java compiler about them.
An import statement usually looks like this:
import ClassNameToImport ;
You specify the import keyword followed by the class that you want to import followed by a semicolon. The class name should be fully qualified, meaning it should include its package.
To import all classes within a package, you can put .* after the package name. For example, this statement imports every class in the com.makotogroup package:
import com.makotogroup.*;
Importing an entire package can make your code less readable, however, so I recommend that you import just the classes you need.
Eclipse simplifies imports
When writing code in the Eclipse editor, you can type the name of a class you want to use, followed by Ctrl+Shift+O. Eclipse figures out which imports you need and adds them automatically. If Eclipse finds two classes with the same name, it displays a dialog box asking you which class you want to add imports for.
developerWorks® ibm.com/developerWorks
Java language basics Trademarks