Friday, April 10, 2009

Declaring Class Members

Declaring Class Members

Access Modifiers

A class can use just two of the four access control levels –
1. public
2. default

A method can have all four access control levels -
1. public
2. protected
3. default
4. private



Public Members
When a method or variable member is declared public, it means all other classes, regardless of the package they belong to, can access the member.That is the class is visible to every one.

There are three ways for accessing method
1. Invoking a method declared in the same class
2. Invoking a method using a reference of the class.
3. Invoking an inherited method

For example :

Class SportsBike //superclass
{
goFast(){}
}

Class Sports extends SportsBike //subclass
{
doWork(){
SportsBike sc=new SportsBike(); // Invoking a method using a reference of the class.
sc.goFast();
}
doMoreStuff(){
goFast(); // Invoking an inherited method
}
}

Look at the following source file:
package book;
import foo.*; // Import all classes in the cert package
class Goo {
public static void main(String[] args) {
Sludge o = new Sludge();
o.testIt();
}
}
Now look at the second file:
package foo;
public class Sludge {
public void testIt() { System.out.println("sludge"); }
}

As you can see, Goo and Sludge are in different packages. However, Goo can invoke the method in Sludge without problems because both the Sludge class and its testIt() method are marked public.

Remember For a subclass, if a member of its superclass is declared public, the subclass inherits that member regardless of whether both classes are in the same package:



Private Members
Members declared as private can't be accessed by code in any class other than the class in which the private member was declared. When a member of superclass is declared private, a subclass can't inherit it.

For example :

Class SportsBike //superclass
{
private goFast(){}
}

Class Sports extends SportsBike //subclass
{
doWork(){
SportsBike sc=new SportsBike(); // Invoking a private method using a reference of the class.
sc.goFast();
}
doMoreStuff(){
goFast(); // Invoking an inherited method
}
}

If you try to execute the above code, compiler will give error
%javac Sports.java
Sports.java:5: Undefined method: goFast()
sc.goFast();

Sports.java:8: Undefined method: goFast()
goFast();
2 errors


Protected and Default Members
The protected and default access control levels are almost identical, but with one critical difference. A default member may be accessed only if the class accessing the member belongs to the same package, whereas a protected member can be accessed (through inheritance) by a subclass even if the subclass is in a different package.

Protected Details
Let's take a look at a protected instance variable (remember, an instance variable is a member) of a superclass.

package ample;
public class Compute {
protected int x = 4; // protected access
}

The preceding code declares the variable x as protected. This makes the variable accessible to all other classes inside the sample package, as well as inheritable by any subclasses outside the package. Now let's create a subclass in a different package, and attempt to use the variable x (that the subclass inherits):

package hello; // Different package
import ample.Compute;
class Print extends Compute {
public void testIt() {
System.out.println("x is " + x); // No problem; Print
// inherits x
Compute c = new Compute (); // Can we access x using the
// c reference?
System.out.println("X in Compute is " + c.x); // Compiler error!
}
}

The preceding code .

%javac -d . hello/Print.java
other/Print.java:7: x has protected access in sample.Calculate
System.out.println("X in Compute is " + c.x);
^
1 error

Default Details
Let's start with the default behavior of a member in a superclass. We'll modify the Parent's member x to make it default.

package sample;
public class Calculate {
int x = 2; //if no access modifier, means default
// (package) access
}

Notice we didn't place an access modifier in front of the variable x. Remember that if you don't type an access modifier before a class or member declaration, the access control is default, which means package level.

Local Variables and Access Modifiers

We can never apply access modifiers to local variables. In fact, there is only one modifier that can ever be applied to local variables—final. If access modifiers are applied to local variables it will not compile. Variables defined in loops, methods without access modifiers are local variables whose scope ends with the termination of container block.

Non-access Member Modifiers

Final Methods

The final keyword prevents a method from being overridden in a subclass, and is often used to enforce the API functionality of a method. This can't-be-overridden restriction provides for
safety and security, but you should use it with great caution.

A typical final method declaration looks like this:
class SuperClass{
public final void showSample() {
System.out.println("One thing.");
}
}

It's legal to extend SuperClass, since the class isn't marked final, but we can't override the final method showSample(), as the following code attempts to do:

class SubClass extends SuperClass{
public void showSample() { // Try to override the final
// superclass method
System.out.println("Another thing.");
}
}

Attempting to compile the preceding code gives us something like this:

%javac FinalTest.java
FinalTest.java:5: The method void showSample() declared in class SubClass cannot override the final method of the same signature declared in class SuperClass.
Final methods cannot be overridden.
public void showSample() { }
1 error



Final Arguments
Method arguments are the variable declarations that appear in between the parentheses in a method declaration. A typical method declaration with multiple arguments looks like this:

public Record getRecord(int fileNumber, final int recordNumber) {}

In this example, the variable recordNumber is declared as final, which of course means it can't be modified within the method.

An abstract method is a method that's been declared (as abstract) but not implemented. In other words, the method contains no functional code.
Abstract method looks like this :
public abstract void showSample();

Notice that the abstract method ends with a semicolon instead of curly braces. It is illegal to have even a single abstract method in a class that is not explicitly declared abstract! Look at the following illegal class:

public class IllegalClass{
public abstract void doIt();
}

The preceding class will produce the following error if you try to compile it:

IllegalClass.java:1: class IllegalClass must be declared
abstract.
It does not define void doIt() from class IllegalClass.
public class IllegalClass{
1 error

Three different clues tell you it's not an abstract method:
1. The method is not marked abstract.
2. The method declaration includes curly braces, as opposed to ending in a semicolon. In other words, the method has a method body.
3. The method provides actual implementation code.
Any class that extends an abstract class must implement all abstract methods of the superclass, unless the subclass is also abstract. The rule is this:
The first concrete subclass of an abstract class must implement all abstract methods of the superclass.


Synchronized Methods
The synchronized keyword indicates that a method can be accessed by only one thread at a time.
A typical synchronized declaration looks like this:
public synchronized Record retrieveInfo(int id) { }

You should also know that the synchronized modifier can be matched with any of the four access control levels.

Native Methods
The native modifier indicates that a method is implemented in platform-dependent code, often in C.
The native is a modifier (thus a reserved keyword) and that native can be applied only to methods—not classes, not variables, just methods.
Note that a native method's body must be a semicolon (;) (like abstract methods), indicating that the implementation is omitted.

Strictfp Methods
strictfp forces floating points (and any floating-point operations) to adhere to the IEEE 754 standard. With strictfp, you can predict how your floating points will behave regardless of the underlying platform the JVM is running on. The downside is that if the underlying platform is capable of supporting greater precision, a strictfp method won't be able to take advantage of it.

You can apply this keyword either on a class or all individual methods of that class.

0 comments:

About This Blog

This Blog is all about Java and programming.This blog is written by Vaibhav Pandey(Read More about him) .He is a Computer Science Graduate .You can contact the author at javatute@gmail.com for any suggestion or Query.You can also contact the author for advertising on this blog.All the material presented here is the property of author and its reproduction in any form is strictly prohibited.

Disclaimer:-Download links provided here are not of author in any means.These are found over the Internet.
Page copy protected against web site content infringement by Copyscape

  © Blogger templates The Professional Template by Ourblogtemplates.com 2008

Back to TOP