Java Basics code and rules

Components of a class:

Package statement

Import statements

/*
  Comments
*/

class declaration {
  Variables
  //Comments
  Constructors()
  Methods()
  Nested classes {}
  Nested interfaces {}
  Enum
}

A comment can precede a package statement.

Class declaration:

Compulsory:

Keyword class – case sensitive
Name of the class
class body – {}

Optional:

Access modifier, e.g. public
Nonaccess modifier, e.g. final
Keyword extends
Keyword implements

Within a class you have:

Variables, these are instance variables or instance attributes – apply to the object only
Methods, used to manipulate the instance variables
Constructors, used to create and initialise the objects of a class

You can define a class in a single file or multiple classes in one file, these (classes and interfaces) can be defined in any order.

If you have a file (example.java) with the following:

interface myInterface1 {

}
class MyClass1 {

}
interface myInterface2 {

}
public class MyClass2 {

}
public interface myInterface3 {

}

This will NOT compile because:
1 – defining a public class of MyClass2 should be in a file of MyClass2.java
2 – defining a public interface myInterface3 should be in a file of myInterface3.java

You can either:

1 – rename the class and interface to example
2 – change the access to non-public

Example:

interface myInterface1 {

}
class MyClass1 {

}
interface myInterface2 {

}
class MyClass2 {

}
public interface example {

}

Only one package per source file.

Executable classes are those which contain a main method.

public class MyExecutableClass {
       public static void main(String args[]) {
            System.out.println("Hello, I am an executable class!!!");
       }
}

main method rules:
Must be public
Must be static
Must be named main
Must be a void
Must accept String array or variable e.g.

public class MyExecutableClass {
	public static void main(String... args) { 
		System.out.println("Hello, I am an executable class!!!");
	}
}

Other examples:

public static void main(String[] callMeAnything)
public static void main(String callMeAnything[])

//Also this works
static public void main(String callMeAnything[])

These produce errors:

//This is a runtime error
static public void main(String[] arguments[])
//This is a compile error
static void public main(String args[])
Packages

The rules:
package names should be lowercase
package and subpackage names separated by ‘.’
com is commercial, followed by company name, then categories and subcategories
package statement is the first in a source file (classes and interfaces) //Comments can appear though
one package statement per file
All classes and interfaces belong to the package defined in the file

The import statement enables you to use simple names instead of using fully qualified names.

importing classes with the same name won’t compile:

import java.util.Date;
import java.sql.Date;

class example {
     
}

Unlike C or C++ importing a class doesn’t add to the size of a .class file.

import java.util.*  //imports all classes and interfaces

However it is not recursive, you cannot import classes / interfaces from a subpackage with the *.

If you don’t specify a package then there is the default package, so if the class is in the same directory it can be referenced, e.g.:

filename person.java

class person {

}

filename house.java

class house {
     person p;
}

This compiles because the files are in the same directory (or referenced) e.g.:

javac tt/person.java house.java //this compiles

import static used to import individual static members of a class, e.g.

import static java.lang.Math.PI;

public class example {
    public static void main(String[] args) {
         System.out.println(PI);
   }
}
Access modifiers

There are four access modifiers:

public
protected
default
private

Public access table:

Anyone can see.

Same package Separate package
Derived classes true true
Unrelated classes true true

Protected access table:

Accessible only to classes and interfaces in the same package
And all derived classes

Example:

file …/people/Person.java

package people;

public class Person {
     protected String name;
}

file …/Home.java

package building;

import people.Person;

public class Home {
     public Home() {
           Person p = new Person();

           p.name = "test";  //compile error as this is protected and in another package
     }
}
Same package Separate package
Derived classes true true
Unrelated classes true false

Default access table:

Only accessible to classes and interfaces in the same package.

file …/people/Person.java

package people;

public class Person {
     int age;
     protected String name;
}

file …/Home.java

package building;

import people.Person;

public class Home {
     public Home() {
           Person p = new Person();
           p.age = 100; //compile error as this is default, we are in a different package
           p.name = "test";  //compile error as this is protected and in another package
     }
}
Same package Separate package
Derived classes true false
Unrelated classes true false

If you define a class as default, it cannot be accessed outside of that package (the default one) – like an inaccessible island.

Private access table:

Private members defined within a class are only accessible within that class.

file …/people/Person.java

package people;

public class Person {
     private void countHairs() {}
     int age;
     protected String name;
}

file …/Home.java

package building;

import people.Person;

public class Home {
     public Home() {
           Person p = new Person();
           p.countHairs(); //compile error as this is a private to Person
           p.age = 100; //compile error as this is default, we are in a different package
           p.name = "test";  //compile error as this is protected and in another package
     }
}
Same package Separate package
Derived classes false false
Unrelated classes false false
Nonaccess modifiers

Specifically:

abstract
final
static

Abstract

prefixing abstract to the definition of a class makes it a abstract class, which cannot be instantiated. A abstract class may or may not have abstract methods.

An interface is an abstract object by default. The compiler adds abstract to the definition of an interface, you can if you want.

An abstract method does not have a body:

abstract class example {
    private string name;
    public void getName() {}  //This is NOT an abstract method, it has an empty body
    public abstract void jump();  //This is a abstract method
}

Final

A class marked as final cannot be extended by another class:

final class Person {}
class Worker extends Person {}
//This code will not compile because Person is final

An interface cannot be marked final, it is abstract.

A final variable is assigned a value once, and cannot be changed. You can call methods on a final variable e.g.

class Example {
    final StringBuilder test = new StringBuilder("abc");
    Example() {
        test.append("xyz"); //all fine
        test = new StringBuilder();  //Won't compile!
    }
}

A final method in a base case cannot be overwritten e.g.

  class Person {
    final void greeting() {
        System.out.println("Why hello there");
    }
  }

  class Worker extends Person {
    void greeting() {
        System.out.println("How do");  //This fails to compile
    }
  }
}

Static

Makes the variable in a class applicable to all instances of the class, e.g.

class Example {
   String name;
   static int amount;
}

class test {
   public static void main(String[] args) {
       Example e1 = new Example();
       Example e2 = new Example();

       e1.name = "Example One";
       e2.name = "Example Two";

       e1.amount = 100;
       e2.amount = 200;

       System.out.println(e1.name);     //This will print Example One
       System.out.println(e2.name);     //This will print Example Two
       System.out.println(e1.amount);   //This will print 200
       System.out.println(e2.amount);  //This will print 200
       System.out.println(Example.amount);  //What does this print? Well it prints 200!
   }
}

Static and final can be used to define a constant:

class Example {
     public static final int WIDTH = 100;  //This is standard practice for constants
}

class Test {
    public static void Main (String[] args) {
         int w = Example.WIDTH;
    }
}

Static Methods

class Example {
    String name;
    private static int amount;

    static int getAmount() {
        return amount;
    }
}

Static methods and variables cannot access non-static variables:

class Example_static {
   String name;

   String getName() {
      return name;
   }

   static String staticName = getName();  //This fails to compile!
}

However, non-static can access static:

class Example_static {
   String name;
   private static int amount;

   static int getAmount() {
      return amount;
   }

   int nonStaticGetAmount() {
       return amount;
   }
}

Static methods/variables cannot access the instance members.

reference: http://www.manning.com/gupta/

Advertisements

Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: