Você está na página 1de 20

What is Android?

Android is a software stack for mobile devices that includes an operating system, middleware and key applications. The Android SDK provides the tools and APIs necessary to begin developing applications on the Android platform using the Java programming language.

Android Architecture
The following diagram shows the major components of the Android operating system. Each section is described in more detail below

Applications
Android will ship with a set of core applications including an email client, SMS program, calendar, maps, browser, contacts, and others. All applications are written using the Java programming language

Application Framework
By providing an open development platform, Android offers developers the ability to build extremely rich and innovative applications. Developers are free to take advantage of the device hardware, access location information, run background services, set alarms, add notifications to the status bar, and much, much more. Developers have full access to the same framework APIs used by the core applications. The application architecture is designed to simplify the reuse of components; any application can publish its capabilities and any other application may then make use of those capabilities (subject to security constraints enforced by the framework). This same mechanism allows components to be replaced by the user. Underlying all applications is a set of services and systems, including: A rich and extensible set of Views that can be used to build an application, including lists, grids, text boxes, buttons, and even an embeddable web browser Content Providers that enable applications to access data from other applications (such as Contacts), or to share their own data A Resource Manager, providing access to non-code resources such as localized strings, graphics, and layout files A Notification Manager that enables all applications to display custom alerts in the status bar An Activity Manager that manages the lifecycle of applications and provides a common navigation backstack

Libraries
Android includes a set of C/C++ libraries used by various components of the Android system. These capabilities are exposed to developers through the Android application framework. Some of the core libraries are listed below: System C library - a BSD-derived implementation of the standard C system library (libc), tuned for embedded Linux-based devices Media Libraries - based on PacketVideo's OpenCORE; the libraries support playback and recording of many popular audio and video

formats, as well as static image files, including MPEG4, H.264, MP3, AAC, AMR, JPG, and PNG Surface Manager - manages access to the display subsystem and seamlessly composites 2D and 3D graphic layers from multiple applications LibWebCore - a modern web browser engine which powers both the Android browser and an embeddable web view SGL - the underlying 2D graphics engine 3D libraries - an implementation based on OpenGL ES 1.0 APIs; the libraries use either hardware 3D acceleration (where available) or the included, highly optimized 3D software rasterizer FreeType - bitmap and vector font rendering SQLite - a powerful and lightweight relational database engine available to all applications

Android Runtime
Android includes a set of core libraries that provides most of the functionality available in the core libraries of the Java programming language. Every Android application runs in its own process, with its own instance of the Dalvik virtual machine. Dalvik has been written so that a device can run multiple VMs efficiently. The Dalvik VM executes files in the Dalvik Executable (.dex) format which is optimized for minimal memory footprint. The VM is registerbased, and runs classes compiled by a Java language compiler that have been transformed into the .dex format by the included "dx" tool. The Dalvik VM relies on the Linux kernel for underlying functionality such as threading and low-level memory management.

Linux Kernel
Android relies on Linux version 2.6 for core system services such as security, memory management, process management, network stack, and driver model. The kernel also acts as an abstraction layer between the hardware and the rest of the software stack.

Application Fundamentals
Android applications are written in the Java programming language. The Android SDK tools compile the codealong with any data and resource filesinto an Android package, an archive file with an .apk suffix. All the code in a single .apk file is considered to be one application and is the file that Android-powered devices use to install the application.

Application Components
Application components are the essential building blocks of an Android application. Each component is a different point through which the system can enter your application. Not all components are actual entry points for the user and some depend on each other, but each one exists as its own entity and plays a specific roleeach one is a unique building block that helps define your application's overall behavior. There are four different types of application components. Each type serves a distinct purpose and has a distinct lifecycle that defines how the component is created and destroyed. Here are the four types of application components: Activities An activity represents a single screen with a user interface. For example, an email application might have one activity that shows a list of new emails, another activity to compose an email, and another activity for reading emails. Although the activities work together to form a cohesive user experience in the email application, each one is independent of the others. As such, a different application can start any one of these activities (if the email application allows it). For example, a camera application can start the activity in the email application that composes new mail, in order for the user to share a picture.

Services A service is a component that runs in the background to perform longrunning operations or to perform work for remote processes. A service does not provide a user interface. For example, a service might play music in the background while the user is in a different application, or it might fetch data over the network without blocking user interaction with an activity. Another component, such as an activity, can start the service and let it run or bind to it in order to interact with it. Content providers A content provider manages a shared set of application data. You can store the data in the file system, an SQLite database, on the web, or any other persistent storage location your application can access. Through the content provider, other applications can query or even modify the data (if the content provider allows it). For example, the Android system provides a content provider that manages the user's contact information. As such, any application with the proper permissions can query part of the content provider to read and write information about a particular person. Content providers are also useful for reading and writing data that is private to your application and not shared. For example, the Note Pad sample application uses a content provider to save notes.

Broadcast receivers A broadcast receiver is a component that responds to system-wide broadcast announcements. Many broadcasts originate from the systemfor example, a broadcast announcing that the screen has turned off, the battery is low, or a picture was captured. Applications can also initiate broadcastsfor example, to let other applications know that some data has been downloaded to the device and is available for them to use. Although broadcast receivers don't display a user interface, they may create a status bar notification to alert the user when a broadcast event occurs. More commonly, though, a broadcast receiver is just a "gateway" to other components and is intended to do a very minimal amount of work. For instance, it might initiate a service to perform some work based on the event. Android Libraries Android offers a number of APIs for developing your applications. The following list of core APIs should provide an insight into whats available; all Android devices will offer support for at least these APIs: android.util The core utility package contains low-level classes like specialized containers, string formatters, and XML parsing utilities. android.os The operating system package provides access to basic operating system services like message passing, interprocess communication, clock functions, and debugging. android.graphics The graphics API supplies the low-level graphics classes that support canvases, colors, and drawing primitives, and lets you draw on canvases. android.text The text processing tools for displaying and parsing text. android.database Supplies the low-level classes required for handling cursors when working with databases. android.content The content API is used to manage data access and publishing by providing services for dealing with resources, content providers, and packages. android.view Views are the core user interface class. All user interface elements are constructed using a series of Views to provide the user interaction components. android.widget Built on the View package, the widget classes are the heres one we created

earlier user-interface elements for you to use in your applications. They include lists, buttons, and layouts. com.google.android.maps A high-level API that provides access to native map controls that you can use within your application. Includes the MapView control as well as the Overlay and MapController classes used to annotate and control your embedded maps. android.app A high-level package that provides access to the application model. The application package includes the Activity and Service APIs that form the basis for all your Android applications. android.provider To ease developer access to certain standard Content Providers (such as the contacts database), the Provider package offers classes to provide access to standard databases included in all Android distributions. android.telephony The telephony APIs give you the ability to directly interact with the devices phone stack, letting you make, receive, and monitor phone calls, phone status, and SMS messages. android.webkit The WebKit package features APIs for working with Web-based content, including a WebView control for embedding browsers in your activities and a cookie manager.

The Android Application Life Cycle


Unlike most traditional environments, Android applications have no control over their own life cycles. Instead, application components must listen for changes in the application state and react accordingly, taking particular care to be prepared for untimely termination.As mentioned before, by default, each Android application is run in its own process thats running a separate instance of Dalvik. Memory and process management of each application is handled exclusively by the run time. Android aggressively manages its resources, doing whatever it takes to ensure that the device remains responsive. This means that processes (and their hosted applications) will be killed, without warning if necessary, to free resources for higher-priority applications generally those that are interacting directly with the user at the time. The prioritization process is discussed in the next section.

Understanding Application Priority and Process States


The order in which processes are killed to reclaim resources is determined by the priority of the hosted applications. An applications priority is equal to its highest-priority component.Where two applications have the same priority, the process that has been at a lower priority longest will be killed fi rst. Process priority is also affected by interprocess dependencies; if an application has a dependency on a Service or Content Provider supplied by a second application, the secondary application will have at least as high a priority as the application it supports. All Android applications will remain running and in memory until the system needs its resources for other applications. The following figure shows the priority tree used to determine the order of application termination

Its important to structure your application correctly to ensure that its priority is appropriate for the work its doing. If you dont, your application could be killed while its in the middle of something important. The following list details each of the application states shown in Figure 3-3, explaining how the state is determined by the application components comprising it:

Active Processes Active (foreground) processes are those hosting applications with components currently interacting with the user. These are the processes Android is trying to keep responsive by reclaiming resources. There are generally very few of these processes, and they will be killed only as a last resort. Active processes include: Activities in an active state; that is, they are in the foreground and responding to user events. Activities, Services, or Broadcast Receivers that are currently executing an onReceive event handler. Services that are executing an onStart, onCreate, or onDestroy event handler. Visible Processes Visible, but inactive processes are those hosting visible Activities. As the name suggests, visible Activities are visible, but they arent in the foreground or responding to user events. This happens when an Activity is only partially obscured (by a non-full-screen or transparent Activity). There are generally very few visible processes, and theyll only be killed in extreme circumstances to allow active processes to continue. Started Service Processes Processes hosting Services that have been started. Services support ongoing processing that should continue without a visible interface. Because Services dont interact directly with the user, they receive a slightly lower priority than visible Activities. They are still considered to be foreground processes and wont be killed unless resources are needed for active or visible processes Background Processes Processes hosting Activities that arent visible and that dont have any Services that have been started are considered background processes. There will generally be a large number of background processes that Android will kill using a last-seen-fi rst-killed pattern to obtain resources for foreground processes. Empty Processes To improve overall system performance, Android often retains applications in memory after they have reached the end of their lifetimes. Android maintains this cache to improve the start-up time of applications when theyre re-launched. These processes are routinely killed as required.

Further reading at

developer.android.com.

Note: The codings used in the Video Tutorial are also available in developer.android.com, The code used in the Video tutorial are really tough and can't be understood by android development newbies ,

but those are used to give you a sense about what we can do with android.

Appendix: Object Oriented Programming with JAVA


Since the Android applications are written in java you should familiar with the Java programming language, this appendix explains some of the basic object oriented concept of Java Introduction to Object-Oriented Programming If you've never used an object-oriented programming language before, you'll need to learn a few basic concepts before you can begin writing any code. This lesson will introduce you to objects, classes, inheritance, interfaces, and packages. Each discussion focuses on how these concepts relate to the real world, while simultaneously providing an introduction to the syntax of the Java programming language.

What Is an Object?
An object is a software bundle of related state and behavior. Software objects are often used to model the real-world objects that you find in everyday life. This lesson explains how state and behavior are represented within an object, introduces the concept of data encapsulation, and explains the benefits of designing your software in this manner.

What Is a Class?
A class is a blueprint or prototype from which objects are created. This section defines a class that models the state and behavior of a real-world object. It intentionally focuses on the basics, showing how even simple classes can cleanly model state and behavior.

What Is Inheritance?
Inheritance provides a powerful and natural mechanism for organizing and structuring your software. This section explains how classes inherit state and behavior from their superclasses, and explains how to derive one class from another using the simple syntax provided by the Java programming language.

What Is an Interface?
An interface is a contract between a class and the outside world. When a class implements an interface, it promises to provide the behavior published by that interface. This section defines a simple interface and explains the necessary changes for any class that implements it. Objects To work with OOP, you should be able to identify three key characteristics of objects: The object's behavior what can you do with this object, or what methods can you apply to it? The object's state how does the object react when you apply those methods? The object's identity how is the object distinguished from others that may have the same behavior and state?

Each object stores information about what it currently looks like. This is the object's state. An object's state may change over time, but not spontaneously. A change in the state of an object must be a consequence of method calls. (If the object state changed without a method call on that object, someone broke encapsulation.) However, the state of an object does not completely describe it, because each object has a distinct identity. For example, in an order-processing system, two orders are distinct even if they request identical items. Notice that the individual objects that are instances of a class always differ in their identity and usually differ in their state. These key characteristics can influence each other. For example, the state of an object can influence its behavior. (If an order is "shipped" or "paid," it may reject a method call that asks it to add or remove items. Conversely, if an order is

"empty," that is, no items have yet been ordered, it should not allow itself to be shipped.) Bundling code into individual software objects provides a number of benefits, including: Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system. Information-hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world. Code re-use: If an object already exists (perhaps written by another software developer), you can use that object in your program. This allows specialists to implement/test/debug complex, task-specific objects, which you can then trust to run in your own code. Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine. Classes All code that you write in Java is inside a class. The standard Java library supplies several thousand classes for such diverse purposes as user interface design, dates and calendars, and network programming. Nonetheless, you still have to create your own classes in Java to describe the objects of the problem domains of your applications and to adapt the classes that are supplied by the standard library to your own purposes. Encapsulations Encapsulation (sometimes called data hiding) is a key concept in working with objects. Formally, encapsulation is nothing more than combining data and behavior in one package and hiding the implementation of the data from the user of the object. The data in an object are called its instance fields, and the procedures that operate on the data are called its methods. A specific object that is an instance of a class will have specific values for its instance fields. The set of those values is the current state of the object. Whenever you invoke a message on an object, its state may change. Relationships Between Classes The most common relationships between classes are Dependence ("usesa") Aggregation ("hasa") Inheritance ("isa") The dependence, or "usesa" relationship, is the most obvious and also the most

general. For example, the Order class uses the Account class because Order objects need to access Account objects to check for credit status. But the Item class does not depend on the Account class, because Item objects never need to worry about customer accounts. Thus, a class depends on another class if its methods manipulate objects of that class. The aggregation, or "has-a" relationship, is easy to understand because it is concrete; for example, an Order object contains Item objects. Containment means that objects of class A contain objects of class B. The inheritance, or "is-a" relationship, expresses a relationship between a more special and a more general class. For example, a RushOrder class inherits from an Order class. The specialized RushOrder class has special methods for priority handling and a different method for computing shipping charges, but its other methods, such as adding items and billing, are inherited from the Order class. In general, if class A extends class B, class A inherits methods from class B but has more capabilities. Inheritance When you extend an existing class, the new class has all the properties and methods of the class that you extend. You supply new methods and data fields that apply to your new class only. The concept of extending a class to obtain another class is called inheritance. Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio. Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this example, Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses: The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from: class MountainBike extends Bicycle { // new fields and methods defining a mountain bike would go here }

This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make it unique. This makes code for your subclasses easy to read. However, you must take care to properly document the state and behavior that each superclass defines, since that code will not appear in the source file of each subclass. Working with Statics Adding static fields to a class Creating static methods Creating classes that can be instantiated Using static initializers A static method is a method that isnt associated with an instance of a class. Instead, the method belongs to the class itself. As a result, you can call the method without first creating a class instance. Understanding Static Fields and Methods According to my handy Websters dictionary, the word static has several different meanings. Most of them relate to the idea of being stationary or unchanging. For example, a static display is a display that doesnt move. Static electricity is an electrical charge that doesnt flow. A static design is a design that doesnt change. The term static as used by Java doesnt mean unchanging. For example, you can create a static field, and then assign values to it as a program executes. Thus, the value of the static field can change. To further confuse things, the word static can also mean interference, as in radio static that prevents you from hearing music clearly on the radio. But in Java, the term static doesnt have anything to do with interference or bad reception. So what does the term static mean in Java? Its used to describe a special type of field or method that isnt associated with a particular instance of a class. Instead, static fields and methods are associated with the class itself. That means you dont have to create an instance of the class to access a static field or methods. Instead, you access a static field or method by specifying the class name, not a variable that references an object. Working with Static Fields A static field is a field thats declared with the static keyword, like this: private static int ballCount; Note that the position of the static and visibility keywords (private and public, as well as protected) are interchangeable. As a result, the following statement works as well: static private int ballCount; As a convention, most programmers tend to put the visibility keyword first. Note that you cant use the static keyword within a class method. Thus, the following code wont compile: static private void someMethod() { static int x; }

In other words, fields can be static, but local variables cant. You can provide an initial value for a static field: private static String district = Northwest; Static fields are created and initialized when the class is first loaded. That happens when a static member of the class is referred to or when an instance of the class is created, whichever comes first. Another way to initialize a static field is to use a static initializer, Using Static Methods A static method is a method declared with the static keyword. Like static fields, static methods are associated with the class itself, not with any particular object created from the class. As a result, you dont have to create an object from a class before you can use static methods defined by the class. The best-known static method is main, which is called by the Java runtime to start an application. The main method must be static, which means that applications are by default run in a static context. One of the basic rules of working with static methods is that you cant access a non-static method or field from a static method. Thats because the static method doesnt have an instance of the class to use to reference instance methods or fields. For example, the following code wont compile: public class TestClass { private int x = 5; // an instance field public static void main(String[] args) { int y = x; // error: wont compile } } Preventing Instances Sometimes, you want to create a class that cant be instantiated at all. Then, the class consists entirely of static fields and methods. A good example in the Java API is the Math class. Its methods provide utility-type functions that arent really associated with a particular object. You may occasionally find the need to create similar classes yourself. For example, you might create a class with static methods for validating input data. Or, you might create a database access class that has static methods to retrieve data from a database. You dont need to create instances of either of these classes. You can use a simple trick to prevent anyone from instantiating a class. To create a class instance, you have to have at least one public constructor. If you dont provide a constructor in your class, Java automatically inserts a default constructor, which happens to be public. All you have to do to prevent a class instance from being created, then, is to provide a single private constructor, like

this: public class Validation { private Validation() {} // prevents instances // static methods and fields go here } Now, because the constructor is private, the class cant be instantiated. Incidentally, the Math class uses this technique to prevent you from creating instances from it. Heres an actual snippet of code from the Math class: public final class Math { /** * Dont let anyone instantiate this class. */ private Math() {} I figure if this trick is good enough for the folks who wrote the Math class, its good enough for me. Static initializer blocks that you can use to initialize instance variables. Initializer blocks arent executed until an instance of a class is created, so you cant count on them to initialize static fields. After all, you might access a static field before you create an instance of a class.

static { statements... } As you can see, a static initializer is similar to an initializer block, but begins with the word static. Like an initializer block, you code static initializers in the class body but outside of any other block, such as the body of a method or constructor. The first time you access a static member such as a static field or a static method, any static initializers in the class are executed provided you havent already created an instance of the class. Thats because the static initializers are also executed the first time you create an instance. In that case, the static initializers are executed before the constructor is executed. If a class has more than one static initializer, theyre executed in the order in which they appear in the program. Heres an example of a class that contains a static initializer: class StaticInit { public static int x; static

{ x = 32; } // other class members such as constructors and // methods go here... } This example is pretty trivial. In fact, you can achieve the same effect just by assigning the value 32 to the variable when it is declared. However, suppose you had to perform a complicated calculation to determine the value of x, or suppose its value comes from a database? In that case, a static initializer can be very useful. Abstract classes Java lets you declare that a method or an entire class is abstract, which means that the method has no body. An abstract method is just a prototype for a method: a return type, a name, a list of parameters, and (optionally) a throws clause. To create an abstract method, you specify the modifier abstract and replace the method body with a semicolon: public abstract int hit(int batSpeed); Here, the method named hit is declared as an abstract method that returns an int value and accepts an int parameter. A class that contains at least one abstract method is called an abstract class, and must be declared with the abstract modifier on the class declaration. For example: public abstract class Ball { public abstract int hit(int batSpeed); } If you omit the abstract modifier from the class declaration, the Java compiler coughs up an error message to remind you that the class must be declared abstract. An abstract class cant be instantiated. Thus, given the preceding declaration, the following line doesnt compile: Ball b = new Ball(); // error: Ball is abstract The problem here isnt with declaring the variable b as a Ball. Its using the new keyword with the Ball class in an attempt to create a Ball object. Because Ball is an abstract class, you can use it to create an object instance. You can create a subclass from an abstract class like this: public class BaseBall extends Ball { public int hit(int batSpeed)

{ // code that implements the hit method goes here } } When you subclass an abstract class, the subclass must provide an implementation for each abstract method in the abstract class. In other words, it must override each abstract method with a non-abstract method. (If it doesnt, the subclass is also abstract, so it too cannot be instantiated.) Abstract classes are useful when you want to create a generic type that is used as the superclass for two or more subclasses, but the superclass itself doesnt represent an actual object. For example, if all employees are either salaried or hourly, creating an abstract Employee class makes sense, and then use it as the base class for the SalariedEmployee and HourlyEmployee subclasses. Interface An interface is similar to an abstract class. However, it can only include abstract methods and final fields (constants), and it cant be used as a base class. Instead, a class implements an interface by providing an implementation for each method declared by the interface. Interfaces have two advantages over inheritance: Interfaces are easier to work with than inheritance, because you dont have to worry about providing any implementation details in the interface. A class can extend only one other class, but it can implement as many interfaces as you need. The following sections describe the details of creating and using interfaces. Creating a basic interface Heres a basic interface that defines a single method, named Playable, that includes a single method named play: public interface Playable { void play(); } This interface declares that any class that implements the Playable interface must provide an implementation for a method named play that accepts no parameters and doesnt return a value. This interface has a few interesting details: The interface itself is declared as public so that it can be used by other classes. Like a public class, a public interface must be declared in a file with the same name. Thus, this interface must be in a file named Playable.java. The name of the interface (Playable) is an adjective. Most interfaces are named

using adjectives rather than nouns because they describe some additional capability or quality of the classes that implement the interface. Thus, classes that implement the Playable interface represent objects that can be played.In case you havent been to English class in a while, an adjective is a word that modifies a noun. You can convert many verbs to adjectives by adding able to the end of the word. For example: playable, readable, drivable, and stoppable. This type of adjective is commonly used for interface names. Another common way to name interfaces is to combine an adjective with a noun to indicate that the interface adds some capability to a particular type of object. For example, you can call an interface that provides methods unique to card games CardGame. This interface might have methods such as deal, shuffle, and getHand. All the methods in an interface are assumed to be public and abstract. If you want, you can code the public and abstract keywords on interface methods. However, thats considered bad form, because it might indicate that you think the default is private and not abstract. Implementing an interface To implement an interface, a class must do two things: It must specify an implements clause on its class declaration. It must provide an implementation for every method declared by the interface. For example, heres a class that implements the Playable interface: public class TicTacToe implements Playable { // additional fields and methods go here public void play() { // code that plays the game goes here } // additional fields and methods go here } Here, the declaration for the TicTacToe class specifies implements Playable. Then, the body of the class includes an implementation of the play method. A class can implement more than one interface: public class Hearts implements Playable, CardGame { // must implement methods of the Playable // and CardGame interfaces } Polymorphism Overloading

Overriding Overloading Methods A Java class can contain two or more methods with the same name, provided those methods accept different parameters. This is called overloading and is one of the keys to building flexibility into your classes. With overloading, you can anticipate different ways someone might want to invoke an objects functions, and then provide overloaded methods for each alternative. The term overloading is accurate, but a little unfortunate. Normally, when you say something is overloaded, theres a problem. For example, I once saw a picture of a Volkswagen Jetta loaded down with 3,000 pounds of lumber. (You can find the picture courtesy of Snopes.com, the Urban Legend Reference Page Web site, at www.snopes.com/photos/lumber.aspThats a classic example of overloading. You dont have to worry about Java collapsing under the weight of overloaded methods. Youre already familiar with several classes that have overloaded methods, though you may not realize it. For example, the PrintWriter class (which you access via System.out) defines ten different versions of the println method that allow you to print different types of data. The following lines show the method declaration for each of these overloads: void println() void println(boolean x) void println(char x) void println(char[] x) void println(double x) void println(float x) void println(int x) void println(long x) void println(Object x) void println(String x) The basic rule when creating overloaded methods is that every method must have a unique signature. A methods signature is the combination of its name and the number and types of parameters it accepts. Thus, each of the println methods has a different signature because although each has the same name, each accepts a different parameter type. Two things that are not a part of a methods signature are The methods return type: You cant code two methods with the same name and parameters but with different return types. The names of the parameters: All that matters to the method signature are the types of the parameters and the order in which they appear. Thus, the following two methods have the same signature: double someMethodOfMine(double x, boolean y) double someMethodOfMine(double param1, Boolean param2) Overriding Methods

If a subclass declares a method that has the same signature as a public method of the base class, the subclass version of the method overrides the base class version of the method. This technique lets you modify the behavior of a base class to suit the needs of the subclass. For example, suppose you have a base class named Game that has a method named play. The base class, which doesnt represent any particular game, implements this method: public class Game { public void play() { } } Then, you declare a class named Chess that extends the Game class, but provides an implementation for the play method: public class Chess extends Game { public void play() { System.out.println(I give up. You win.); } } Note that to override a method, three conditions have to be met: The class must extend the class that defines the method you want to override. The method must be declared in the base class with public access. You cant override a private method. The method in the subclass must have the same signature as the method in the base class. In other words, the name of the method and the parameter types must be the same.

Você também pode gostar