We're very excited to announce the immediate availability of the JavaFX 1.3 platform. This release represents an important upgrade to the product and delivers a range of performance and functional improvements, including:
* New and enhanced support for UI controls, CSS skinning, and programmatic layout
* Performance improvements in the JavaFX Runtime
* New NetBeans IDE 6.9 Beta with improved editing and an updated JavaFX Composer plug-in
* New features and enhanced performance in JavaFX Production Suite
* A native JavaFX font family called Amble
* Support for the development of TV applications, including a new TV emulator
* Availability of the mobile emulator on the Mac platform
Check out What's new in JavaFX 1.3 for more details and additional enhancements
It might be hard to believe that JavaFX has only been in the market for less than one and a half years, it certainly is for us! In that time, we've built out the foundation for mobile with a deployment ready runtime, delivered a library of UI controls to make it substantially easier to build out consistent user interfaces, and were able to entice developers to download over 400,000 copies of our tools by our 1.2 release. We've released a beta of the JavaFX Composer to provide visual-editing for form-based UIs with an exceptionally positive response and seen the community rally around the platform with projects like JFXtras, numerous blogs, and over a dozen books. We've also been very excited to see companies like the Vancouver Organizing Committee for the 2010 Olympic and Paralympic Winter Games adopting the technology for commercial products and services, and we've got another well-known customer that we're excited to start talking to you about shortly!
But lets get back to the JavaFX 1.3 release. As we began working with some of these high-profile customers, we found they were really pushing the limits of JavaFX. Since our 1.2 release we've spent a lot of time carefully evaluating our performance goals to meet the needs of these customers and have heavily optimized in the following areas:
* Bind performance: 2-3x faster
* Applet start-up time: 20% faster (with Java SE 6u18+)
* Text Rendering: 5-10x faster (frames per second/FPS)
* Highly complex animations: up to 10x faster (FPS)
* Memory usage: 20-33% reduction (real-world apps, w/ Java SE 6u18+)
* UI Controls: 50% faster, 33%-50% less memory (typical)
Lets take a quick look at a few of these. Binding has often been described as one of the more powerful features in JavaFX, but many developers found they had to use it sparingly due to performance considerations. In JavaFX 1.3 we've implemented substantial improvements in the way JavaFX handles binding and have seen tremendous payoffs, in particular with applications that make heavy usage of this feature.
Start-up time is another area where we've made substantial improvements. First, it’s important to understand that we measure start-up time in two ways. We measure both cold-start (the first time a user loads an applet, includes download and initialization) and warm-start (subsequent launches of the applet). Cold-start is critical, because it’s the user’s first impression and it’s also where we've achieved the most improvements with 1.3. To improve start-up time, we implemented a number of optimizations throughout the stack, including the JRE and the JavaFX runtime. Basic applications running on systems with a recent version of the JRE (Java SE 6u18+) launch 20% faster and complex applications start nearly twice as fast! Obviously your mileage will vary depending on the specifics of your application.
Animation performance has been another area of focus in JavaFX 1.3. In one of our more extreme benchmarks, we applied animations to 900 objects simultaneously. In JavaFX 1.2 this would have resulted in a paltry 6 FPS. With JavaFX 1.3 we are now seeing an impressive 67 FPS - that's over 10x faster! Unless you are using a ton of objects in your application you probably won't see this kind of performance gain but we've effectively removed animations as a performance bottleneck so developers can use them much more freely in their applications. A similar benchmark with 500 animated objects managed to deliver a 5x improvement.
JavaFX 1.3 Released, Improves User Experiences
Shakespeare
Today, Shakespeare enthusiasts can still visit the site of the house which has now been turned into an Elizabethan garden. Nash’s House, the building next door, still remains and serves as a museum dedicated to Tudor life and New Place. Both sites are cared for by the Shakespeare Birthplace Trust.
New Place
New Place, once described as a “pretty house of brick and timber,” was built towards the end of the 15th century and bought by Shakespeare in 1597 – although he did not live there until his retirement from London in 1610.
On display in the adjoining museum is a sketch of New Place by George Vertue showing the main house (where Shakespeare lived) enclosed by a courtyard. These street-facing buildings would have been the servant’s quarters.
Francis Gastrell
New Place was demolished and rebuilt in 1702 by the new owner. The house was rebuilt in brick and stone but it only survived another 57 years. In 1759, the new owner, Reverend Francis Gastrell, quarreled with the town authorities over taxation and Gastrell had the house permanently demolished in 1759.
New Place was never again rebuilt and only the foundations of the house remain.
Shakespeare’s Mulberry Tree
Gastrell also caused controversy when he removed Shakespeare’s mulberry tree. It is said that Shakespeare planted a mulberry tree in the gardens of New Place, which posthumously attracted visitors. Gastrell complained that it made the house damp and had it chopped for firewood – or perhaps, Gastrell wanted to deter the visitors!
Thomas Sharpe, an enterprising local clockmaker and carpenter, bought most of the wood and carved Shakespeare mementos from it. The museum in Nash’s House displays some of the artifacts said to be made from Shakespeare’s mulberry tree.
SQL Injection
SQL bang is an advance in which awful cipher is amid into strings that are after anesthetized to an instance of SQL Server for parsing and execution. Any action that constructs SQL statements should be advised for bang vulnerabilities because SQL Server will assassinate all syntactically accurate queries that it receives. Even parameterized abstracts can be manipulated by a accomplished and bent attacker.
The primary anatomy of SQL bang consists of absolute admittance of cipher into user-input variables that are concatenated with SQL commands and executed. A beneath absolute advance injects awful cipher into strings that are destined for accumulator in a table or as metadata. When the stored strings are after concatenated into a activating SQL command, the awful cipher is executed.
The bang action works by anon absolute a argument cord and appending a fresh command. Because the amid command may accept added strings added to it afore it is executed, the captive terminates the injected cord with a animadversion mark "--". Subsequent argument is abandoned at beheading time.
The afterward calligraphy shows a simple SQL injection. The calligraphy builds an SQL concern by concatenating hard-coded strings calm with a cord entered by the user:
Copy
var Shipcity;
ShipCity = Request.form ("ShipCity");
var sql = "select * from OrdersTable area ShipCity = '" + ShipCity + "'";
The user is prompted to access the name of a city. If she enters Redmond, the concern accumulated by the calligraphy looks agnate to the following:
SELECT * FROM OrdersTable WHERE ShipCity = 'Redmond'
However, accept that the user enters the following:
Redmond'; bead table OrdersTable--
In this case, the afterward concern is accumulated by the script:
SELECT * FROM OrdersTable WHERE ShipCity = 'Redmond';drop table OrdersTable--'
The semicolon (;) denotes the end of one concern and the alpha of another. The bifold abutment (--) indicates that the blow of the accepted band is a animadversion and should be ignored. If the adapted cipher is syntactically correct, it will be accomplished by the server. When SQL Server processes this statement, SQL Server will aboriginal baddest all annal in OrdersTable area ShipCity is Redmond. Then, SQL Server will bead OrdersTable.
As continued as injected SQL cipher is syntactically correct, analytical cannot be detected programmatically. Therefore, you charge validate all user ascribe and anxiously analysis cipher that executes complete SQL commands in the server that you are using. Coding best practices are declared in the afterward sections in this topic.
Struts Framework
What Is the Struts Framework
The Struts Framework is a standard for developing well-architected Web applications. It has the following features:- Open source
- Based on the Model-View-Controller (MVC) design paradigm, distinctly separating all three levels:
- Model: application state
- View: presentation of data (JSP, HTML)
- Controller: routing of the application flow
- Implements the JSP Model 2 Architecture
- Stores application routing information and request mapping in a single core file,
struts-config.xml
Architecture Overview
All incoming requests are intercepted by the Struts servlet controller. The Struts Configuration filestruts-config.xml
is used by the controller to determine the routing of the flow. This flows consists of an alternation between two transitions: From View to Action | A user clicks on a link or submits a form on an HTML or JSP page. The controller receives the request, looks up the mapping for this request, and forwards it to an action. The action in turn calls a Model layer (Business layer) service or function. |
From Action to View | After the call to an underlying function or service returns to the action class, the action forwards to a resource in the View layer and a page is displayed in a web browser. |
- User clicks on a link in an HTML page.
- Servlet controller receives the request, looks up mapping information in
struts-config.xml
, and routes to an action. - Action makes a call to a Model layer service.
- Service makes a call to the Data layer (database) and the requested data is returned.
- Service returns to the action.
- Action forwards to a View resource (JSP page)
- Servlet looks up the mapping for the requested resource and forwards to the appropriate JSP page.
- JSP file is invoked and sent to the browser as HTML.
- User is presented with a new HTML page in a web browser.
Struts Components
The Controller
This receives all incoming requests. Its primary function is the mapping of a request URI to an action class selecting the proper application module. It's provided by the framework.The struts-config.xml
File
This file contains all of the routing and configuration information for the Struts application. This XML file needs to be in the WEB-INF directory of the application.Action Classes
It's the developer's responsibility to create these classes. They act as bridges between user-invoked URIs and business services. Actions process a request and return an ActionForward object that identifies the next component to invoke. They're part of the Controller layer, not the Model layer.View Resources
View resources consist of Java Server Pages, HTML pages, JavaScript and Stylesheet files, Resource bundles, JavaBeans, and Struts JSP tags.ActionForms
These greatly simplify user form validation by capturing user data from the HTTP request. They act as a "firewall" between forms (Web pages) and the application (actions). These components allow the validation of user input before proceeding to an Action. If the input is invalid, a page with an error can be displayed.Model Components
The Struts Framework has no built-in support for the Model layer. Struts supports any model components:- JavaBeans
- EJB
- CORBA
- JDO
- any other
Introduction to Hibernate Caching
1) Introduction
While working with Hibernate web applications we will face so many problems in its performance due to database traffic. That to when the database traffic is very heavy . Actually hibernate is well used just because of its high performance only. So some techniques are necessary to maintain its performance. Caching is the best technique to solve this problem. In this article we will discuss about, how we can improve the performance of Hibernate web applications using caching.
The performance of Hibernate web applications is improved using caching by optimizing the database applications. The cache actually stores the data already loaded from the database, so that the traffic between our application and the database will be reduced when the application want to access that data again. Maximum the application will works with the data in the cache only. Whenever some another data is needed, the database will be accessed. Because the time needed to access the database is more when compared with the time needed to access the cache. So obviously the access time and traffic will be reduced between the application and the database. Here the cache stores only the data related to current running application. In order to do that, the cache must be cleared time to time whenever the applications are changing. Here are the contents.
* Introduction.
o First-level cache.
o Second-level cache.
* Cache Implementations.
o EHCache.
o OSCache.
o SwarmCache.
o JBoss TreeCache.
* Caching Stringategies.
o Read-only.
o Read-Write.
o Nonstriict read-write.
o Transactional.
* Configuration.
*
* Caching the queries.
* Custom Cache.
o Configuration.
o Implementation :: ExampleCustomCache.
* Something about Caching.
o Performance.
o About Caching.
* Conclusion.
Hibernate uses two different caches for objects: first-level cache and second-level cache..
1.1) First-level cache
First-level cache always Associates with the Session object. Hibernate uses this cache by default. Here, it processes one transaction after another one, means wont process one transaction many times. Mainly it reduces the number of SQL queries it needs to generate within a given transaction. That is instead of updating after every modification done in the transaction, it updates the transaction only at the end of the transaction.
1.2) Second-level cache
Second-level cache always associates with the Session Factory object. While running the transactions, in between it loads the objects at the Session Factory level, so that those objects will available to the entire application, don’t bounds to single user. Since the objects are already loaded in the cache, whenever an object is returned by the query, at that time no need to go for a database transaction. In this way the second level cache works. Here we can use query level cache also. Later we will discuss about it.
2) Cache Implementations
Hibernate supports four open-source cache implementations named EHCache (Easy Hibernate Cache), OSCache (Open Symphony Cache), Swarm Cache, and JBoss Tree Cache. Each cache has different performance, memory use, and configuration possibilities.
2.1) 2.1 EHCache (Easy Hibernate Cache) (org.hibernate.cache.EhCacheProvider)
* It is fast.
* lightweight.
* Easy-to-use.
* Supports read-only and read/write caching.
* Supports memory-based and disk-based caching.
* Does not support clustering.
2.2)OSCache (Open Symphony Cache) (org.hibernate.cache.OSCacheProvider)
* It is a powerful .
* flexible package
* supports read-only and read/write caching.
* Supports memory- based and disk-based caching.
* Provides basic support for clustering via either JavaGroups or JMS.
2.3)SwarmCache (org.hibernate.cache.SwarmCacheProvider)
* is a cluster-based caching.
* supports read-only or nonstrict read/write caching .
* appropriate for applications those have more read operations than write operations.
2.4)JBoss TreeCache (org.hibernate.cache.TreeCacheProvider)
* is a powerful replicated and transactional cache.
* useful when we need a true transaction-capable caching architecture .
3) Caching Stringategies
Important thing to remembered while studying this one is none of the cache providers support all of the cache concurrency strategies.
3.1) Read-only
* Useful for data that is read frequently but never updated.
* It is Simple .
* Best performer among the all.
Advantage if this one is, It is safe for using in a cluster. Here is an example for using the read-only cache strategy.
....
3.2) Read-Write
* Used when our data needs to be updated.
* It’s having more overhead than read-only caches.
* When Session.close() or Session.disconnect() is called the transaction should be completed in an environment where JTA is no used.
* It is never used if serializable transaction isolation level is required.
* In a JTA environment, for obtaining the JTA TransactionManager we must specify the property hibernate.transaction.manager_lookup_class.
* To use it in a cluster the cache implementation must support locking.
Here is an example for using the read-write cache stringategy.
….
….
3.3) Nonstrict read-write
* Needed if the application needs to update data rarely.
* we must specify hibernate.transaction.manager_lookup_class to use this in a JTA environment .
* The transaction is completed when Session.close() or Session.disconnect() is called In other environments (except JTA) .
Here is an example for using the nonstrict read-write cache stringategy.
….
3.4) Transactional
* It supports only transactional cache providers such as JBoss TreeCache.
* only used in JTA environment.
HIBERNATE- BASICS
The J2EE field is agog with excitement about a very popular open-source technology , Hibernate , being elevated to the status of JCP standard. Feedback from J2EE programmers in industry says that knowledge of Hibernate is mandatory for all J2EE aspirants.In this short tutorial , the author attempts to trace the reasons for this new trend & to alert us , to the imminent and dramatic changes in the J2EE landscape.
HIBERNATE is an ORM ( Object-Relational-Mapping) technology. It is an Open-Source and free technology , developed in SourceForge.net. There have been a number of such ORM technologies,in recent past.. TopLink is one such tool , subsequently adopted by Oracle and so proprietary. Hibernate from SourceForge and OJB(Object-Relational-Bridge) from Apache are two well known ORM tools, open-source and free. JDO, also falls within the same category.
Gavin King is the lead for Hibernate and Craig Russell & David Jordan, the lead authors for SUN-sponsored JDO effort. Due to some technical problems, it appears that the majority in JCP favours Hibernate today instead of JDO.At first reading though, the difference is not, all that apparent. The syntax and the approach appear to be almost same, but Hibernate syntax is easier to learn.
It is interesting to note that Craig Russell works for SUN and Gavin King is now with JBoss. It shows that JCP is a democratic community and SUN is not dictating terms except to protect the language and its enterprise-level users.
EJB-3, is the latest version and it is heavily influenced by Hibernate. Some readers equate EJB-3 with Hibernate. Some even equate EJB-3 with JBOSS! Oracle supports EJB-3 proposals and as it is the main Database company in j2ee world, EJB-3 has bright future. J2EE( Java Enterprise Edition) by its very name is an Enterprise level technolgy, and as EJB is the essence of such Enterprise applications,because of the built-in container services offered, the significance of the surging interest in Hibernate can be really appreciated only in association with EJB and hence a detour into EJB is inevitable.
EJB has three types. One type is the SESSION BEAN,residing in ENTERPRISE container, which can be thought of as a function-bean, invoked in RMI-IIOP style.(this is a rough definition). Such session-bean , may be either stateless or stateful. This type of EJB has stood the test of time during the last six years and has even gained wide approval,even for data-access, especially since it fits very well with the emerging XML WebService technology, and is very easy to learn and implement.( The earlier tutorial on EJB as webservice in Feb-2005, in DeveloperIQ illustrates this feature). The stateless bean working in Enterprise container has an exact counter-part in Microsoft COM+(MTS). but the other types are said to be available in MS platform only through third-party extensions.
ORM tools have been sometimes used along with Session beans. The only problem till recently was that they were proprietory and rather costly. But nowadays, very reliable open-source ORM tools are available, and even Richard Monson Haefel ( an acknowledged authority and author on EJB)approves this method as a safe and productive alternative to Entity beans.( page-467..EJB by Haefel-OReilly).
The other branch, the ENTITY BEAN has been less lucky. EJB-1.1,EJB-2.0 and then EJB-2.1 , have meant a number of changes in the specification relating to Entity Beans.
We can say that an Entity bean is an 'Attribute bean' or 'property-bean', with setter and getter methods, invoked in RMI-IIOP style and persisted in Enterprise container. The pattern of defining a typical Javabean is a recurring theme in Java. The same style occurs in BDK,EJB-Entity beans, Struts,JSF and now in Hibernate too. So, it is very important and elegant.
The third branch is Messaging paradigm and MDB. A recent article in the web dubbed the 'RPC' style, on which the previous two types of EJB are based, as stone-age technologies! An Enterprise by its very name implies huge number of customers and concurrent transactions, RPC style being like telephone call, could result in 'line-engaged!' problem.If the call involves the called person referring to some records before replying, it leads to line- blocking.But, messaging style, as in email, atleast ensures that the message has been sent.It is evident that dubbing RPC( read 'telephone') as unsuitable , is over-statement.Sometimes, we desire immediate response,too. By the same token, even XML webservice , if it is really serious, should adopt messaging style and it does.MDB (Message-Driven bean) has weathered the storm and is in fact gaining more and more acceptance.
So, why is it that Entity beans alone were found wanting and the specification keeps on changing?
Entity beans are of two types. CMP & BMP.
CMP stands for Container-Managed Persistence and BMP stands for Bean-managed persistence. Theoretically, the EJB specification does not say anything about the method to be adopted in persisting objects for permanent storage and retrieval. It could be simple object serialization. The database may be object-database or Object-relational database or XML.In practice , however, a database has always meant a Relational Database and its SQL.
In a very complex Enterprise application, we begin with Modelling. Instead of dealing with tables and their complex inter-relations, it is more intuitive to deal with classes and objects. Thus we design our system , 'thinking in objects' and not in tables. So long, as we are dealing with objects in memory or with objects persisted in hard-disk simply as objects, there is no problem, except that object-serialization , especially of complex objects is a slow process. On the other-hand, Relational Database technology is fast, time-tested, well-known and famous. So, the problem is to work with objects in memory but persist the objects in hard disk as relational database.
This is what is known as ORM ( Object-Relational Mapping).If we opt to deal directly with tables only and either read data or manipulate data by session beans, we skip the entire ORM problem.But how practical is it for really complex projects?That is the rationale for the development of Entity Beans in EJB.
In CMP, the coder deals with objects, only in memory. He creates new objects, modifies them, deletes them and views them , all in memory. The task of saving these objects in memory ,to the relational database table is done by the container, automatically. The coder does not write any sql-related code for this.
In BMP, the coder has to write the sql to persist the object in memory to the relational database.
CMP in EJB1.1 was suitable for simple tables, without complex relationships to other tables.CMP avoids all references to the underlying database. So, it is more portable. There is no vendor-lock-in.CMP can persist data to Object- databases also, besides Relational databases.
But, CMP is not always suitable. If the database is some legacy type, which cannot be used with SQL, the database company gives a proprietory code for persistence and such code has to be used in our program to persist data. The facilities given in CMP originally were found to be too elementary and there were complaints.
But, what matters is that CMP makes use of ORM concepts, though the implementation left much to be desired. It did not expose how the EJB vendor implements it.Weblogic,Oracle,IBM WebSphere, SUN ,JBoss , each may implement CMP in any way that they deem fit.Except in special circumstances, it will be better to use CMP, not merely because, it makes the code more portable & is easy to write. Much more important reason is that the EJB container can optimize the performace dramatically, if we adopt CMP.So the developer community wanted to adopt CMP but found it unsuitable for really complex jobs.
And a sizable section of developers found the XML Deployment Descriptors for CMP ,
especially for complex jobs, a bit troublesome and tedious.It can be said that any design which makes us dependent on wizards, is a bad design. Unlike the Deployment Descriptors for Session beans, which can be hand-coded in a jiffy, by just find/replace method in a text editor, the DD for CMP required three XML files, two of them very special to the container used.
In order to improve things, EJB 2.0 proposed a few changes, mainly in the matter of writing CMP. It provided for Relationships. It proposed a simple query language known as 'EJB-QL'. Since, calling an Entity bean through a session bean (Facade pattern) is more efficient , from the viewpoint of minimizing network traffic, the very concept of remote interface for entity beans was questioned and so local interface also was provided for Entity beans.( In a total reversal, there is no local interface in EJB-3! and instead of EJB-QL , Hybernate Query Langauge is taking over in EJB-3).
Even with all these improvements, CMP was found to be less than the ultimate solution. There was no possibility for Inheritance.
Though the container services provided by the EJB container are indispensable in a truly large enterprise application, the J2EE camp is almost vertically split into WebTier & EJB-Tier votaries. The WebTier supporters claim that EJB with its steep learning curve and error prone development environment for developers is not really necessary for most applications. And they would like to have an ORM tool , built into the J2EE specification. For afterall, ORM task is not specific to EJB alone. Even Servlets and JSP could use them. In fact , they have been using them, though the J2EE specification was silent about it. ORM tools like OJB, JDO and Hibernate can be used not only in EJB containers but in webcontainer and even in standalone containers. Gavin King makes it a special point in favour of Hibernate.Making such a tool , a J2EE standard, would make development tasks far easier ,to develop either web-tier application or ejb-tier application. saving us from the medley of classpath to required jars.
In a scathing attack on the complexity and questionable performance of EJB Entity beans (though, unjustifiably on EJB itself), Rod Johnson, prophesies , that in a few years' time, J2EE will cease to include EJB.Whether , we agree or not, it is worth looking into the criticisms against EJB Entity beans ,raised by him.( 'J2EE Development without EJB'-Wrox/Wiley/DreamTech-2004).For, he is proposing the Spring Framework as an alternative to EJB container and the idea is gaining ground.J2EE developers and students may have to re-orient themselves rather abruptly, to remain relevant to industry.
In the next part of this introductory tutorial, we will acquaint ourselves with the basic features of Hibernate.
Kamal Hassan Latest New's
“Rehearsal is key to acceptable acting. Films are fabricated on Rs 50 crore budget. But no one bothers to rehearse. Practice makes a man perfect. Likeswise, rehearsals would hone your acting talent,” the ‘Ulaga Nayagan’ said.
Heaping acclaim on the way dramas are made, he said, “More than 50 rehearsals are captivated for a play, alike admitting it is fabricated on a account from Rs one lakh. But the case is not so in cinema.”
On his coach Balachander, Kamal said, “I developed the addiction of practicing for a role from KB. But for him, I would accept been aloof addition actor, and not the Kamal Haasan you see actuality today. My authority had immense acceptance on me.”
Former Chief Election Commissioner N Gopalaswami, who presented the accolade to the ace director, said, “I accede it an honour to present KB with this award. He is the Jambawan of Tamil cinema.”
Others who were present at the action were AVM Saravanan, Crazy Mohan, S B Kanthan, ‘Madhu’ Balaji, ‘Poovilangu’ Mohan, Renuka, Fathima Babu, Madhuvanthi Arun and Ramesh Vinayakam.
Remember to check before using computer at an unknown place
Information:
New storing device fits at the end of the keyboard cable connecting to the PC specialized to save all typed keys. Mostly could be used in net cafes, exhibitions, hotels and airports therefore be careful especially the people who use the internet in these places to enter their bank accounts online or any other important sites. After you enter the bank account and leave the PC it will be easy to open your account again as all what you have typed has been saved in the Black device. Therefore, you should check the PC for any suspicious piece behind it before using the net in public places for important sites
Inside Java : The Java Virtual Machine
Inside Java offers a glimpse behind the Java platform, and related technologies. This month, we examine the Java Virtual Machine, which allows Java code to be executed on a wide variety of hardware and software environments.
At the heart of the Java platform lies the Java Virtual Machine, or JVM. Most programming languages compile source code directly into machine code, suitable for execution on a particular microprocessor architecture. The difference with Java is that it uses bytecode - a special type of machine code.
Java bytecode executes on a special type of microprocessor. Strangely enough, there wasn't a hardware implementation of this microprocessor available when Java was first released. Instead, the processor architecture is emulated by what is known as a "virtual machine". This virtual machine is an emulation of a real Java processor - a machine within a machine (Figure One). The only difference is that the virtual machine isn't running on a CPU - it is being emulated on the CPU of the host machine.
Figure One - JVM emulation run on a physical CPU
The Java Virtual Machine is responsible for interpreting Java bytecode, and translating this into actions or operating system calls. For example, a request to establish a socket connection to a remote machine will involve an operating system call. Different operating systems handle sockets in different ways - but the programmer doesn't need to worry about such details. It is the responsibility of the JVM to handle these translations, so that the operating system and CPU architecture on which Java software is running is completely irrelevant to the developer.
Figure Two - JVM handles translations
The Java Virtual Machine forms part of a large system, the Java Runtime Environment (JRE). Each operating system and CPU architecture requires a different JRE. The JRE comprises a set of base classes, which are an implementation of the base Java API, as well as a JVM. The portability of Java comes from implementations on a variety of CPUs and architectures. Without an available JRE for a given environment, it is impossible to run Java software.
Differences between JVM implementations
Though implementations of Java Virtual Machines are designed to be compatible, no two JVMs are exactly alike. For example, garbage collection algorithms vary between one JVM and another, so it becomes impossible to know exactly when memory will be reclaimed. The thread scheduling algorithms are different between one JVM and another (based in part on the underlying operating system), so that it is impossible to accurately predict when one thread will be executed over another.
Initially, this is a cause for concern from programmers new to the Java language. However, it actually has very little practical bearing on Java development. Such predictions are often dangerous to make, as thread scheduling and memory usage will vary between different hardware environments anyway. The power of Java comes from not being specific about the operating system and CPU architecture - to do so reduces the portability of software.
Summary
The Java Virtual Machine provides a platform-independent way of executing code, by abstracting the differences between operating systems and CPU architectures. Java Runtime Environments are available for a wide variety of hardware and software combinations, making Java a very portable language. Programmers can concentrate on writing software, without having to be concerned with how or where it will run. The idea of virtual machines is nothing new, but Java is the most widely used virtual machine used today. Thanks to the JVM, the dream of Write Once-Run Anywhere (WORA) software has become a reality.
Inside Java : The Java Programming Language
Inside Java offers a glimpse behind the Java platform, and related technologies. In this month's column, I'll show you an overview of the Java programming language.
Java - an island of Indonesia, a type of coffee, and a programming language. Three very different meanings, each in varying degrees of importance. Most programmers, though, are interested in the Java programming language. In just a few short years (since late 1995), Java has taken the software community by storm. Its phenomenal success has made Java the fastest growing programming language ever. There's plenty of hype about Java, and what it can do. Many programmers, and end-users, are confused about exactly what it is, and what Java offers.
Java is a revolutionary language
The properties that make Java so attractive are present in other programming languages. Many languages are ideally suited for certain types of applications, even more so than Java. But Java brings all these properties together, in one language. This is a revolutionary jump forward for the software industry.
Let's look at some of the properties in more detail: -
*
object-oriented
*
portable
*
multi-threaded
*
automatic garbage collection
*
secure
*
network and "Internet" aware
*
simplicity and ease-of-use
Object-oriented
Many older languages, like C and Pascal, were procedural languages. Procedures (also called functions) were blocks of code that were part of a module or application. Procedures passed parameters (primitive data types like integers, characters, strings, and floating point numbers). Code was treated separately to data. You had to pass around data structures, and procedures could easily modify their contents. This was a source of problems, as parts of a program could have unforeseen effects in other parts. Tracking down which procedure was at fault wasted a great deal of time and effort, particularly with large programs.
In some procedural language, you could even obtain the memory location of a data structure. Armed with this location, you could read and write to the data at a later time, or accidentally overwrite the contents.
Java is an object-oriented language. An object-oriented language deals with objects. Objects contain both data (member variables) and code (methods). Each object belongs to a particular class, which is a blueprint describing the member variables and methods an object offers. In Java, almost every variable is an object of some type or another - even strings. Object-oriented programming requires a different way of thinking, but is a better way to design software than procedural programming.
There are many popular object-oriented languages available today. Some like Smalltalk and Java are designed from the beginning to be object-oriented. Others, like C++, are partially object-oriented, and partially procedural. In C++, you can still overwrite the contents of data structures and objects, causing the application to crash. Thankfully, Java prohibits direct access to memory contents, leading to a more robust system.
Portable
Most programming languages are designed for a specific operating system and processor architecture. When source code (the instructions that make up a program) are compiled, it is converted to machine code which can be executed only on one type of machine. This process produces native code, which is extremely fast.
Another type of language is one that is interpreted. Interpreted code is read by a software application (the interpreter), which performs the specified actions. Interpreted code often doesn't need to be compiled - it is translated as it is run. For this reason, interpreted code is quite slow, but often portable across different operating systems and processor architectures.
Java takes the best of both techniques. Java code is compiled into a platform-neutral machine code, which is called Java bytecode. A special type of interpreter, known as a Java Virtual Machine (JVM), reads the bytecode, and processes it. Figure One shows a disassembly of a small Java application. The bytecode, indicated by the arrow, is represented in text form here, but when compiled it is represented as bytes to conserve space.
Figure One - Bytecode disassembly for "HelloWorld"
The approach Java takes offers some big advantages over other interpreted languages. Firstly, the source code is protected from view and modification - only the bytecode needs to be made available to users. Secondly, security mechanisms can scan bytecode for signs of modification or harmful code, complimenting the other security mechanisms of Java. Most of all though, it means that Java code can be compiled once, and run on any machine and operating system combination that supports a Java Virtual Machine (JVM). Java can run on Unix, Windows, Macintosh, and even the Palm Pilot. Java can even run inside a web browser, or a web server. Being portable means that the application only has to be written once - and can then execute on a wider range of machines. This saves a lot of time, and money.
Multi-threaded
If you've ever written complex applications in C, or PERL, you'll probably have come across the concept of multiple processes before. An application can split itself into separate copies, which run concurrently. Each copy replicates code and data, resulting in increased memory consumption. Getting the copies to talk together can be complex, and frustrating. Creating each process involves a call to the operating system, which consumes extra CPU time as well.
A better model is to use multiple threads of execution, referred to as threads for short. Threads can share data and code, making it easier to share data between thread instances. They also use less memory and CPU overhead. Some languages, like C++, have support for threads, but they are complex to use. Java has support for multiple threads of execution built right into the language. Threads require a different way of thinking, but can be understood very quickly. Thread support in Java is very simple to use, and the use of threads in applications and applets is quite commonplace.
Automatic garbage collection
No, we're not talking about taking out the trash (though a computer that could literally do that would be kind of neat). The term garbage collection refers to the reclamation of unused memory space. When applications create objects, the JVM allocates memory space for their storage. When the object is no longer needed (no reference to the object exists), the memory space can be reclaimed for later use.
Languages like C++ force programmers to allocate and deallocate memory for data and objects manually. This adds extra complexity, but also causes another problem - memory leaks. When programmers forget to deallocate memory, the amount of free memory available is decreased. Programs that frequently create and destroy objects may eventually find that there is no memory left. In Java, the programmer is free from such worries, as the JVM will perform automatic garbage collection of objects.
Secure
Security is a big issue with Java. Since Java applets are downloaded remotely, and executed in a browser, security is of great concern. We wouldn't want applets reading our personal documents, deleting files, or causing mischief. At the API level, there are strong security restrictions on file and network access for applets, as well as support for digital signatures to verify the integrity of downloaded code. At the bytecode level, checks are made for obvious hacks, such as stack manipulation or invalid bytecode. The strong security mechanisms in Java help to protect against inadvertent or intentional security violations, but it is important to remember that no system is perfect. The weakest link in the chain is the Java Virtual Machine on which it is run - a JVM with known security weaknesses can be prone to attack. It is also worth noting that while there have been a few identified weaknesses in JVMs, they are rare, and usually fixed quickly.
Network and "Internet" aware
Java was designed to be "Internet" aware, and to support network programming. The Java API provides extensive network support, from sockets and IP addresses, to URLs and HTTP. It's extremely easy to write network applications in Java, and the code is completely portable between platforms. In languages like C/C++, the networking code must be re-written for different operating systems, and is usually more complex. The networking support of Java saves a lot of time, and effort.
Java also includes support for more exotic network programming, such as remote-method invocation (RMI), CORBA and Jini. These distributed systems technologies make Java an attractive choice for large distributed systems.
Simplicity and ease-of-use
Java draws its roots from the C++ language. C++ is widely used, and very popular. Yet it is regarded as a complex language, with features like multiple-inheritance, templates and pointers that are counter-productive. Java, on the other hand, is closer to a "pure" object-oriented language. Access to memory pointers is removed, and object-references are used instead. Support for multiple-inheritance has been removed, which lends itself to clearer and simpler class designs. The I/O and network library is very easy to use, and the Java API provides developers with lots of time-saving code (such as networking and data-structures). After using Java for awhile, most developers are reluctant to return to other languages, because of the simplicity and elegance of Java.
Summary
Java provides developers with many advantages. While most of these are present in other languages, Java combines all of these together into one language. The rapid growth of Java has been nothing short of phenomenal, and shows no signs (yet!) of slowing down. In next month's column, I'll talk more about the heart of Java - the Java Virtual Machine.
Object Aggressive Concepts in Java – Allotment 2
Object Aggressive Programming (OOP) is a able force in the mural ofcomputer application development today. Some say (quite correctly, in my opinion) that the development efforts abaft largecomputer application projects such as Microsoft Office artlessly would not be attainable to administer after the modularity and cipher reclaim fabricated attainable by today's commodity aggressive languages. Others aloof adopt OOP because it pays added adequate and it's added fun!
Whatever your affidavit for acquirements the attempt of OOP, Java is an ideal accent in which to get your anxiety wet. It's affable abundant to beginners that you shouldn't be afflicted by complicated syntax if you're adequate with basal programming concepts, and yet it is a absolutely complete, commodity aggressive language, clashing abounding added Web development languages such as Perl, PHP, and ASP, which alone accommodate commodity aggressive features.
This commodity is both the fourth in SitePoint's alternation on developing activating Web sites with Java, and the added of two genitalia that focus on teaching you what you charge to apperceive about Commodity Aggressive Programming to booty abounding advantage of what the Java accent has to offer. If you acquire not apprehend the antecedent accessories in this series, I would absolutely acclaim abetment up and starting from the beginning, as the concepts presented actuality await on your ability of all that has appear before.
In Allotment One, we looked at the basal concepts of classes, Objects, properties, and methods. We developed a simple chic alleged Timberline as able-bodied as a affairs to instantiate a few Copse and analysis out their acme acreage and their abound method. After a abrupt attending at inheritance, area we developed a bracket of Timberline alleged CoconutTree, we looked at the issues you will face aback artful and comparing Altar in Java. In Allotment Two, we'll aces up adapted area we larboard off by acquirements some added avant-garde types of methods and properties. We'll apprentice how these may be acclimated to architecture added adequate classes that affectation some important appearance of adequate commodity orientedcomputer application design. In addition, we'll acquire a attending at some avant-garde concepts in chic design, and I'll accommodate an account of chic packages, which let you adapt your classes into groups.
With all the formalities out of the way, let's get started!
Passing Ambit and Returning Values
Most of the methods we acquire looked at so far acquire been of a adapted type. Actuality is a acknowledgment of one such method, the pickNut adjustment for the CoconutTree chic that we developed in Allotment One:
attainable abandoned pickNut() {
numNuts = numNuts – 1;
}
What makes this, and the added methods we acquire looked at so far, adapted is the actuality that it doesn't crave any parameters, nor does it acknowledgment a value. As you'll appear to ascertain as we attending at added applied examples of Java classes after in this series, best methods do one or both of these.
Parameters are pieces of advice that charge be provided aback invoking a activity to absolutely specify the activity to be taken. For example, if we capital to accomplish the pickNut adjustment aloft added powerful, we could accord it a constant to announce the cardinal of basics to be picked:
attainable abandoned pickNut(int numberToPick) {
numNuts = numNuts – numberToPick;
}
In this fresh adaptation of the pickNut method, we acquire authentic that the activity takes an accumulation (int) parameter, the amount of which is stored in a capricious alleged numberToPick. The cipher of the adjustment afresh uses it as the cardinal to be subtracted from the numNuts property. Thus, we can now aces as abounding basics as we appetite from a CoconutTree with a distinct abracadabra of the pickNut method. Actuality are a few sample invocations of pickNut:
CoconutTree ct = fresh CoconutTree(); // Fresh timberline
// Presumably we abound a few basics first...
ct.pickNut(1); // Picks one nut
ct.pickNut(5); // picks bristles basics
ct.pickNut(0); // Doesn't do annihilation
int basics = 10;
ct.pickNut(nuts); // Picks ten basics
ct.pickNut(-1); // Picks -1 nut (??)
As this aftermost band demonstrates, there is a botheration with this method. Aback it accepts any accumulation as the cardinal of basics to be picked, there is annihilation endlessly a affairs that uses it to aces a abrogating cardinal of nuts. Looking at the cipher of our method, this would absolutely aloof add added basics to the tree, but we should not acquiesce operations on our commodity that do not accomplish faculty in the absolute world. Addition operation that would not accomplish faculty would be to aces added basics than there are attainable for acrimonious on the tree! With the absolute code, this would aftereffect in our timberline advertisement a abrogating cardinal of basics -- hardly a astute situation.
These two problems acknowledge an important affair aback designing methods that crave parameters. You should consistently accomplish abiding that the amount anesthetized to a adjustment makes faculty afore application it. Even if you're alone planning on application a chic in your own programs, it's hasty attainable to balloon what ethics will and will not account problems aback you aren't blockage the ethics automatically.
The afterward adapted adaptation of pickNut checks the constant to accomplish abiding that it is not negative, and that it is no beyond than the cardinal of basics on the tree:
attainable abandoned pickNut(int numberToPick) {
if (numberToPick < 0) return; // Cannot aces abrogating cardinal
if (numberToPick > numNuts) return; // Not abundant basics
numNuts = numNuts – numberToPick;
}
The acknowledgment command anon terminates the method. Thus, the operation of acrimonious the basics (subtracting from the numNuts property) will alone action if both of the altitude in the if statements are false. This ensures that our two constraints are met afore we acquiesce the acrimonious operation to go ahead.
One botheration still remains, here. How can the cipher that invokes the pickNut adjustment apperceive whether the acrimonious operation was successful? After all, if the acrimonious operation fails because one of the constraints was not satisfied, we don't appetite our affairs to backpack on as if it was able to aces the nuts. To boldness this issue, we charge already afresh adapt pickNut; this time, we will accomplish it acknowledgment a value:
attainable boolean pickNut(int numberToPick) {
if (numberToPick < 0) acknowledgment false;
if (numberToPick > numNuts) acknowledgment false;
numNuts = numNuts – numberToPick;
acknowledgment true;
}
Not alone can methods acquire constant ethics aback they are invoked, but they can additionally accelerate a amount aback by allegorical the amount as allotment of the acknowledgment command. In this fresh adaptation of the code, we acquire replaced the chat abandoned in the adjustment acknowledgment with the chat boolean. This indicates that the activity will acknowledgment a Boolean (true/false) amount aback it terminates. In this accurate case, we acquire adopted to acknowledgment accurate if the acrimonious operation succeeded, and apocryphal if it bootless for any reason. This allows us to anatomy the cipher of the affairs that invokes the adjustment as follows:
if (!ct.pickNut(10)) {
System.out.println("Error: Could not aces 10 nuts!");
System.exit();
}
nutsInHand = nutsInHand + 10;
The action of the if account calls pickNut with a constant amount of 10, and afresh checks its acknowledgment amount to see if it's apocryphal (note the ! operator). If it is, an absurdity bulletin is printed out. The System.exit adjustment afresh terminates the affairs immediately, which is a reasonable acknowledgment to an abrupt error. Otherwise, the affairs gain as usual.
Another accepted use for acknowledgment ethics is to actualize methods that accomplish some accepted abacus and acknowledgment the aftereffect for the affairs to use. There will be affluence added examples in the blow of this alternation for you to apprentice from.
Class Packages
For abundant of Allotment One, we formed with a chic alleged Tree. Now, while Timberline isn't an abnormally aboriginal name for a class, it fits the chic perfectly. The botheration is that the aforementioned name ability fit addition chic aloof as well, and you'll acquire a allotment battle on your hands. Such conflicts aren't too austere aback you get to address all your own classes; however, aback you charge to accompany in a set of classes that addition abroad wrote for use in your program, things can get messy.
Consider, for example, what would appear if you've advised all of the classes to handle the argumentation for a affairs that will clue the sales of buttons for clothing. In such a case it would be accustomed to acquire a chic alleged Button, but afresh your bang-up tells you he or she wants a nice, graphical user interface for the program. To your dismay, you acquisition that the chic congenital into Java for creating buttons on user interfaces is alleged (you estimated it) Button. How can this battle be bound after accepting to go aback through your cipher and change every advertence to your Button class?
Class bales to the rescue! Java provides chic bales (usually alleged aloof 'packages') as a way of alignment calm classes according to their purpose, the aggregation that wrote them, or whatever added belief you like. As continued as you ensure that your Button chic is not in the aforementioned amalgamation as Java's congenital Button class, you can use both classes in your affairs after any conflicts arising.
By default, classes you actualize abide in the absence package, an bearding amalgamation area all classes that are not assigned bales go. For best of your programs it is safe to leave your classes in the absence package. All of Java's congenital classes as able-bodied as best of the classes you will acquisition attainable on the Internet and from othercomputer application vendors are aggregate into packages, so you usually don't acquire to anguish about your classes' names clashing with those of added classes in the absence package.
You will appetite to accumulation your classes into bales if you intend to reclaim them in approaching projects (where fresh chic names may affray with those you appetite to reuse), or if you appetite to administer them for use by added developers (where their chic names may affray with your own). To abode your chic in a package, you artlessly acquire to accord the name of the amalgamation on a band at the top of your file. The assemblage is to use "com." followed by the name of your aggregation as your amalgamation name. For example, classes that we advance at SitePoint.com are aggregate in the com.sitepoint amalgamation by abacus the afterward band to the top of our java files:
package com.sitepoint;
Be acquainted that aback a chic that resides in a amalgamation is compiled, the chic book will be placed in a agenda based on the name of the package. For example, accumulation Button.java that belongs to amalgamation com.sitepoint creates the Button.class book in the com/sitepoint/ subdirectory of the accepted directory. To run or contrarily accomplish use of a chic in such a package, you should accredit to it as if it were in the agenda that contains the com subdirectory. So, to run the com.sitepoint.MyProgram class, you should go to the agenda absolute com (which contains sitepoint, which in about-face contains the MyProgram.class file) and type:
C:\javadev> java com.sitepoint.MyProgram
Java will automatically attending for com/sitepoint/MyProgram.class.
As it turns out, the Button chic congenital into Java is absolutely in the java.awt package, which additionally contains all of the added classes for creating basal graphical user interfaces in Java (AWT stands for Abstract Windowing Toolkit, in case you were wondering). Thus, the absolutely able name of Java's Button chic is java.awt.Button. To accomplish use of this chic after your affairs cerebration that you're apropos to your own Button class, you can use this abounding name instead. For example:
// Actualize a Java Button
java.awt.Button b = fresh java.awt.Button();
In fact, Java requires that you use the abounding name of any chic that is not in the aforementioned amalgamation as the accepted class!
But what if your affairs doesn't acquire a Button chic to affray with the one congenital into Java? Spelling out the abounding chic name every time agency a lot of added typing. To save yourself this annoyance, you can acceptation the chic into the accepted amalgamation by putting the afterward band at the top of your .java book (just beneath the amalgamation line, if any):
import java.awt.Button;
Once it's imported, you can use the chic by its abbreviate name (Button) as if it were allotment of the aforementioned amalgamation as your class.
Another adequate affection allows you to acceptation an absolute chic amalgamation into the accepted package. This comes in attainable afresh aback creating user interfaces for your program, because to actualize a adapted interface you ability calmly acquire to use a dozen or added classes from the java.awt package, and advertisement anniversary by name on a abstracted acceptation band can become as annoying as accounting the abounding name of the chic in your code. To acceptation the absolute java.awt amalgamation for use in a chic after accepting to blazon their abounding names, you can add the afterward band to the top of the file:
import java.awt.*;
The java.lang package, which contains all the best basal classes of the Java accent (e.g. the Arrangement class, which we acquire been application in the anatomy of the System.out.println() adjustment to affectation argument on the screen), is automatically alien into every Java book automatically.
Before you can acceptation or use the absolutely able name of a chic to admission it from addition package, it charge be declared public. Classes, by default, are alone attainable for use by cipher in the aforementioned package. Obviously, this is not a adorable limitation if you are planning to administer your cipher for use by others, or reclaim your classes in assorted projects; therefore, any chic that you apprehend actuality advantageous to cipher alfresco of the class' amalgamation should be fabricated public. Accomplishing this is as simple as abacus the keyword attainable to the actual alpha of the chic declaration. For example, it would accomplish faculty to acknowledge our Timberline chic public:
package com.sitepoint;
public chic Timberline {
...
}
The aforementioned goes for CoconutTree:
package com.sitepoint;
public chic CoconutTree extends Timberline {
...
}
Access Ascendancy Modifiers
As we acquire aloof seen, a chic can be fabricated attainable to acquiesce cipher alfresco of its amalgamation to accomplish use of it. Chic members, which accommodate backdrop and methods, can be analogously adapted to ascendancy admission to them. Like classes, associates acquire a absence admission ambience that restricts admission to cipher aural the aforementioned package. Consider the afterward sample declarations:
int numNuts = 0;
boolean pickNut(int numberToPick) {
...
}
Even if the chic is declared public, the amount of the aloft numNuts acreage (assuming it is declared as the acreage of an Commodity class) may alone be accessed or adapted by cipher in the aforementioned package. Similarly, the pickNut adjustment apparent aloft may alone be invoked by cipher in the aforementioned amalgamation as the class.
As with classes, backdrop and methods may be declared public:
attainable int numNuts = 0;
attainable boolean pickNut(int numberToPick) {
...
}
Any cipher (from any chic in any package) can admission and adapt a attainable acreage amount or adjure a attainable method.
Properties and methods acquire two added admission settings that classes do not have. The aboriginal is private:
clandestine int numNuts = 0;
clandestine boolean pickNut(int numberToPick) {
...
}
Only cipher in the aforementioned chic can admission clandestine backdrop and methods. If you appetite to abundance advice in an commodity that is alone advantageous to the commodity itself or added altar of the aforementioned class, or if you appetite to bind admission to the advice (as we'll see in the abutting section, this is allotment of adequate chic design!), afresh you should use a clandestine acreage for it. Likewise, methods that accomplish centralized calculations or are contrarily not advantageous to added classes should be declared private.
The final admission ambience that methods and backdrop may booty is protected:
adequate int numNuts = 0;
adequate boolean pickNut(int numberToPick) {
...
}
The adequate approach is actual agnate to the absence mode, in that it refuses admission to cipher alfresco of the class' package, but it introduces one exception: subclasses of the accepted chic (i.e. classes that extend this class) may additionally admission adequate members.
Distinguishing the situations in which anniversary admission ascendancy ambience is adapted takes a little experience. It's appetizing at aboriginal to aloof acknowledge aggregate attainable to save yourself the agitation of annoying aback commodity is attainable and aback it isn't. While this will absolutely work, it is absolutely not in the spirit of commodity aggressive programming. Cipher that you plan to reclaim or distribute, especially, will account from actuality assigned the best akin admission ascendancy settings that are appropriate. One acumen for this is illustrated in the afterward section.
Encapsulation with Accessors
Previously, we adapted the pickNut adjustment so that it would not acquire too aerial a number, which would account our CoconutTree to anticipate it independent a abrogating cardinal of coconuts. But there is a abundant simpler way to aftermath this unrealistic situation:
CoconutTree ct = fresh CoconutTree();
ct.numNuts = -10;
How can we assure Commodity backdrop from actuality assigned ethics like this that don't accomplish sense? The band-aid is to accomplish the backdrop themselves private, and alone admittance admission to them application methods. Actuality is an adapted adaptation of our CoconutTree chic that makes use of this technique:
1 amalgamation com.sitepoint;
2
3 attainable chic CoconutTree extends Timberline {
4 clandestine int numNuts = 0;
5
6 attainable abandoned growNut() {
7 numNuts = numNuts + 1;
8 }
9
10 attainable boolean pickNut(int numToPick) {
11 if (numToPick < 0) acknowledgment false;
12 if (numToPick > numNuts) acknowledgment false;
13 numNuts = numNuts – numToPick;
14 acknowledgment true;
15 }
16
17 attainable int getNumNuts() {
18 acknowledgment numNuts;
19 }
20
21 attainable boolean setNumNuts(int newNumNuts) {
22 if (newNumNuts < 0) acknowledgment false;
23 numNuts = newNumNuts;
24 acknowledgment true;
25 }
26 }
As you can see on band 4, the numNuts acreage is now private, acceptation that alone cipher aural this chic is accustomed to admission it. The growNut and pickNut backdrop abide unchanged; they can abide to amend the numNuts acreage anon (the constraints in pickNut ensure that the amount of numNuts charcoal legal). Aback we still appetite cipher to be able to actuate the cardinal of basics in a tree, we acquire added a attainable getNumNuts adjustment that artlessly allotment the amount of the numNuts property. As for ambience the cardinal of nuts, we acquire added a setNumNuts adjustment that takes an accumulation amount as a parameter. That amount is arrested to ensure that it is absolute or aught (since we can't acquire a abrogating cardinal of nuts) and afresh sets the numNuts acreage to this fresh value.
These two fresh methods, getNumNuts and setNumNuts, are accepted as accessor methods; that is, they are methods acclimated for accessing a property. Accessors are actual archetypal of a well-designed object. Even in cases area any amount is acceptable, you should accomplish your objects' backdrop clandestine and accommodate accessor methods to admission them. Accomplishing this allows your programs to affectation an important affection of commodity aggressive programming alleged encapsulation.
Encapsulation agency that the centralized representation of an commodity is afar from the interface it presents to added altar in your program. In added words, a programmer that uses your chic alone needs to apperceive what the attainable methods do, not how they work. The advantage is that you can change how your chic works to advance achievement or add fresh appearance after breaking any cipher that relies on the methods provided by your aboriginal class.
For example, if you absitively you capital to represent anniversary attic as an alone commodity of chic Attic instead of application a distinct accumulation capricious to accumulate count, you could accomplish the all-important changes and still acquire the aforementioned four methods as the accomplishing above. Old cipher that was accounting with the aboriginal interface in apperception would abide to assignment as before, while fresh cipher could booty advantage of the fresh appearance (which would of advance be provided by fresh methods).
As an exercise, carbon the Timberline chic so that it accurately encapsulates its acme property.
Constructors
A architect is a adapted blazon of adjustment that is invoked automatically aback an commodity is created. Constructors acquiesce you to specify advertence ethics for properties, and added such initialization details.
Consider already afresh our Timberline class; specifically, the acknowledgment of its acme acreage (which should now be clandestine and accompanied by accessor methods):
clandestine int acme = 0;
It's the "= 0" allotment that apropos us here. Why should all fresh copse be of acme zero? Application a constructor, we can let users of this chic specify the antecedent acme of the tree. Here's what it looks like:
clandestine int height;
attainable Tree(int height) {
if (height < 0) this.height = 0;
abroad this.height = height;
}
At aboriginal glance, this looks aloof like a accustomed method. There are two differences, however:
· Constructors never acknowledgment a value; thus, they don't acquire a acknowledgment blazon (void, int, boolean, etc.) in their declaration.
· Constructors acquire the aforementioned name as the chic they are acclimated to initialize. Aback we are autograph the Timberline class, its architect charge additionally be alleged Tree. By convention, this is the alone case area a adjustment name should be capitalized.
So analytic this band by line, we are declaring a attainable architect that takes a distinct constant and assigns its amount to an accumulation capricious height. Agenda that this is not the commodity acreage height, as we shall see momentarily. The added band checks to see if the acme capricious is beneath than zero. If it is, we set the acme acreage of the timberline to aught (since we don't appetite to acquiesce abrogating timberline heights). If not, we accredit the amount of the constant to the property.
Notice that aback we acquire a bounded capricious alleged height, we charge accredit to the acme acreage of the accepted commodity as this.height. this is a adapted capricious in Java that consistently refers to the commodity in which the accepted cipher is executing. If this confuses you, you could instead name the constructor's constant commodity like newHeight. You'd afresh be able to accredit to the Commodity acreage artlessly as height.
Since the Timberline chic now has a architect with a parameter, you charge specify a amount for that constant aback creating fresh Trees:
Tree myTree = fresh Tree(10); // Antecedent acme 10
Overloaded Methods
Sometimes it makes faculty to acquire two altered versions of the aforementioned method. For example, aback we adapted the pickNut adjustment in the CoconutTree chic to crave a constant that authentic the cardinal of basics to pick, we absent the accessibility of actuality able to aces a distinct nut by aloof calling pickNut(). Java absolutely lets you acknowledge both versions of the adjustment ancillary by ancillary and determines which one to use by the cardinal and blazon of the ambit anesthetized aback the adjustment is called. Methods that are declared with added than one adaptation like this are alleged active methods.
Here's how to acknowledge the two versions of the pickNut method:
attainable boolean pickNut() {
if (numNuts == 0) acknowledgment false;
numNuts = numNuts – 1;
acknowledgment true;
}
attainable boolean pickNut(int numToPick) {
if (numToPick < 0) acknowledgment false;
if (numToPick > numNuts) acknowledgment false;
numNuts = numNuts – numToPick;
acknowledgment true;
}
One way to save yourself some accounting is to apprehension that pickNut() is absolutely aloof a adapted case of pickNut(int numToPick); that is, calling pickNut() is the aforementioned as calling pickNut(1), so you can apparatus pickNut() by artlessly authoritative the agnate call:
attainable boolean pickNut() {
acknowledgment pickNut(1);
}
attainable boolean pickNut(int numToPick) {
if (numToPick < 0) acknowledgment false;
if (numToPick > numNuts) acknowledgment false;
numNuts = numNuts – numToPick;
acknowledgment true;
}
Not alone does this save two curve of code, but if you anytime change the way the pickNut adjustment works, you alone acquire to acclimatize one adjustment instead of two.
Constructors can be active in the aforementioned way as accustomed methods. If you absence the accessibility of actuality able to actualize a fresh Timberline of acme zero, you can acknowledge a added architect that takes no parameters:
clandestine int height;
attainable Tree() {
this(0);
}
attainable Tree(int height) {
if (height < 0) this.height = 0;
abroad this.height = height;
}
Note that we acquire already afresh adored ourselves some accounting by implementing the simpler adjustment (Tree()) by invoking a adapted case of the added circuitous adjustment (Tree(0)). In the case of a constructor, however, you alarm it by the adapted name this.
Advanced Inheritance: Cardinal Methods
I covered bequest in Allotment One of this article, but I larboard out one avant-garde affair for the account of brevity that I'd like to awning now: cardinal methods. As you know, an commodity of chic CoconutTree inherits all of the appearance of the Timberline class, on which it is based. Thus, CoconutTrees acquire abound methods aloof like Copse do.
But what if you capital CoconutTrees to sprout fresh coconuts aback they grew? Sure, you could alarm the growNut adjustment every time you acquired a CoconutTree to grow, but it would be nicer if you could amusement Copse and CoconutTrees absolutely the aforementioned way (i.e. alarm their abound method) and acquire them both do what they're declared to do aback altar of their blazon grow.
To acquire the aforementioned adjustment do commodity altered in a subclass, you charge override that adjustment with a fresh analogue in the subclass. Put simply, you can re-declare the abound adjustment in the CoconutTree chic to accomplish it do commodity different! Here's a fresh analogue for abound that you can add to your CoconutTree class:
public abandoned grow() {
height = acme + 1;
growNut();
}
Simple, right? But what if you added fresh functionality to the abound adjustment in the Timberline class? How could you accomplish abiding that this was affiliated by the CoconutTree class? Like in our altercation of active methods, area we implemented a simple adjustment by calling a adapted case of the added complicated method, we can apparatus a fresh analogue for a adjustment in a bracket by apropos to its analogue in the superclass:
attainable abandoned grow() {
super.grow();
growNut();
}
The super.grow() band invokes the adaptation of abound authentic in the superclass, appropriately extenuative us from accepting to reinvent the wheel. This is abnormally attainable aback you are creating a chic that extends a chic for which you do not acquire the antecedent cipher (e.g. a chic book provided by addition developer). By artlessly calling the superclass versions of the methods you are overriding, you can ensure that your altar aren't accident any functionality.
Constructors may be overridden aloof like accustomed methods. Here's a set of constructors for the CoconutTree class, forth with the fresh acknowledgment of the numNuts acreage after an antecedent value:
clandestine int numNuts;
attainable CoconutTree() {
super();
numNuts = 0;
}
attainable CoconutTree(int height) {
super(height);
numNuts = 0;
}
attainable CoconutTree(int height, int numNuts) {
super(height);
if (numNuts < 0) this.numNuts = 0;
abroad this.numNuts = numNuts;
}
The aboriginal two constructors override their equivalents in the Timberline class, while the third is absolutely new. Apprehension that we alarm the architect of the superclass as super(). All three of our constructors alarm a architect in the superclass to ensure that we are not accident any functionality.
Static Members
If you went aback and advised every cipher archetype we acquire apparent so far, there should alone abide one keyword that puzzles you. Surprisingly, it appears in the actual aboriginal commodity in this series, and at the alpha of every Java affairs we acquire accounting so far:
attainable changeless abandoned main(String[] args) {
In case you didn't atom it, the keyword in catechism is static. Both methods and backdrop can be declared static. Changeless associates accord to the chic instead of to Altar of that class. Afore I explain why the capital adjustment is declared static, let's attending at a simpler case.
It ability be advantageous to apperceive the absolute cardinal of Copse that had been created in our program. To this end, we could actualize a changeless acreage alleged totalTrees in the Timberline class, and adapt the architect to access its amount by one every time a Timberline was created. Then, application a changeless adjustment alleged getTotalTrees, we could analysis the amount at any time by calling Tree.getTotalTrees().
Here's the cipher for the adapted Timberline class:
public chic Timberline {
clandestine changeless int totalTrees = 0;
clandestine int height;
attainable Tree() {
this(0);
}
attainable Tree(int height) {
totalTrees = totalTrees + 1;
if (height < 0) this.height = 0;
abroad this.height = height;
}
attainable changeless int getTotalTrees() {
acknowledgment totalTrees;
}
...
}
Static associates are advantageous in two capital situations:
· When you appetite to accumulate clue of some advice aggregate by all associates of a chic (as above).
· When it doesn't accomplish faculty to acquire added than one instance of a acreage or method.
The capital activity is an archetype of the closing case. Aback it doesn't accomplish faculty to acquire added than already instance of the capital activity (i.e. a affairs can alone acquire one program), it is declared static.
Another archetype of a changeless affiliate that we acquire apparent is the out acreage of the Arrangement chic (also accepted as System.out, we acquire acclimated its println adjustment on abounding occasions). Aback there is alone one arrangement on which this affairs is running, it is represented by a chic absolute changeless backdrop (e.g. out) and methods (e.g. exit), rather than an instance of a class.
Don't anguish too abundant if you can't absolutely blanket your arch about the acumen abaft the use of changeless associates in the affairs and the Arrangement classes. As continued as you can butt how the tree-counting archetype aloft keeps clue of the absolute cardinal of Timberline altar created, you're in adequate shape.
Summary
I wouldn't accusation you for activity a little afflicted at this point. If you're annihilation like me, your aboriginal consequence of Commodity Aggressive Programming (OOP) in Java is that it is acutely powerful, acutely complicated, and actual altered from annihilation you acquire formed with before.
Fortunately, you get acclimated to it.
As you chase forth through the blow of this series, the sometimes alarming concepts presented in this commodity will alloy into a accustomed way of alive withcomputer application apparatus that archetypal real-world things and assignment calm in alive means to accomplish the adapted outcome. The added Java you see and address yourself, the added you'll get acclimated to this way of working, and the beneath you'll appetite to acknowledgment to the old way of accomplishing things. Ultimately, Commodity Aggressive Programming is added fun!
You now acquire an finer complete butt of the Java accent itself. What charcoal for you to apprentice afore you can put that ability to applied use is a set of classes. Java includes bales of classes for assuming all sorts of tasks, from architecture graphical user interfaces to creating activating Web sites. In the abutting commodity in this series, I'll acquaint you to the classes accompanying to architecture Java Servlets, the best basal basic of Java-powered activating Web sites.