Sie sind auf Seite 1von 41

Declare Classes

Abstract Class
An abstract class defines an abstract concept which cant be instantiated. We cant create object of abstract class, it can only be inherited. Abstract class normally represents concept with general actions associated with it.

Difference between abstract class and interfaces


Abstract Can have abstract methods and concrete methods Interface

All methods are not by default public An abstract class can extend another abstract class The extended class can override the methods of its super class and its hierarchy All abstract methods must have abstract access modifier

Can have only method signatures and static final members All methods by default abstract and public An interface can extend another interface but not a class An implementing class can implement multiple interfaces All methods in an interface must not have abstract access modifier

The following examples illustrate the differences:


abstract class Shape { abstract void area(); abstract void perimeter(); void someMethod() // concrete method { .. } } interface Shape { void area(); void perimeter(); }

Nested Classes
The Java programming language allows you to define a class within another class. Such a class is called a nested class and is illustrated here: class OuterClass { ... class NestedClass
{ ... }

Why Use Nested Classes?


It is a way of logically grouping classes that are only used in one place. It increases encapsulation. Nested classes can lead to more readable and maintainable code.

Logical grouping of classesIf a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.
Increased encapsulationConsider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world. More readable, maintainable codeNesting small classes within top-level classes places the code closer to where it is used.

Static Nested Classes


A static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class it can use them only through an object reference.

Declare Enums

In prior releases, the standard way to represent an enumerated type was the int Enum pattern: // int Enum Pattern - has severe problems! public static final int SEASON_WINTER = 0; public static final int SEASON_SPRING = 1; public static final int SEASON_SUMMER = 2; public static final int SEASON_FALL = 3;

This pattern has many problems, such as:


Not typesafe - Since a season is just an int you can pass in any other int value where a season is required, or add two seasons together (which makes no sense). No namespace - You must prefix constants of an int enum with a string (in this case SEASON_) to avoid collisions with other int enum types.

In 5.0, the Java programming language gets linguistic support for enumerated types. In their simplest form, these enums look just like their C, C++, and C# counterparts: enum Season { WINTER, SPRING, SUMMER, FALL }

Enum Example
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY

Object Orientation

Inheritance Is-a, Has-a


In OO, the concept of IS-A is based on class inheritance or interface implementation. For example, a Mustang is a type of horse, so in OO terms we can say, "Mustang IS-A Horse." Subaru IS-A Car. Broccoli IS-A Vegetable.

Example
public class Car { // Cool Car code goes here }

public class Subaru extends Car { // Important Subaru-specific stuff goes here // Don't forget Subaru inherits accessible Car members which // can include both methods and variables. }

Has a
HAS-A relationships are based on usage, rather than inheritance. A Horse IS-A Animal. A Horse HAS-A Halter.
public class Animal { } public class Horse extends Animal { private Halter myHalter; }

Object Reference Type Casting


In java object typecasting one object reference can be type cast into another object reference. The cast can be to its own class type or to one of its subclass or superclass types or interfaces. There are compile-time rules and runtime rules for casting in java. There can be 2 casting java scenarios Upcasting Downcasting

Return Type Declarations


Return Types on Overloaded Methods public class Foo { void go() { } } public class Bar extends Foo { String go(int x) { return null; } } NOT allowed to do is this:

Overriding and Return Types


Java 5, you're allowed to change the return type in the overriding method as long as the new return type is a subtype of the declared return type of the overridden (superclass) method. class Alpha { Alpha doStuff(char c) { return new Alpha(); } } class Beta extends Alpha { Beta doStuff(char c) { // legal override in Java 1.5 return new Beta(); } }

Returning a Value
1. You can return null in a method with an object reference return type. public Button doStuff() { return null; } 2. An array is a perfectly legal return type. public String[] go() { return new String[] {"Fred", "Barney", "Wilma"}; } 3. In a method with a primitive return type, you can return any value or variable that can be implicitly converted to the declared return type. public int foo() { char c = 'c'; return c; // char is compatible with int }

4. In a method with a primitive return type, you can return any value or variable that can be explicitly cast to the declared return type. public int foo () { float f = 32.5f; return (int) f; } 5. You must not return anything from a method with a void return type. public void bar() { return "this is it"; // Not legal!! } 6. In a method with an object reference return type, you can return an object type that can be implicitly cast to the declared return type. public Animal getAnimal() { return new Horse(); // Assume Horse extends Animal }
public Object getObject() { int[] nums = {1,2,3}; return nums; // Return an int array, // which is still an object }

Coupling and Cohesion


Cohesion and Coupling deal with the quality of an OO design. Generally, good OO design calls for loose coupling and high cohesion. The goals of OO designs are to make the application Easy to Create Easy to Maintain Easy to Enhance

Coupling
Coupling is the degree to which one class knows about another class. Let us consider two classes class A and class B. If class A knows class B through its interface only

High coupling
class DoTaxes { float rate; float doColorado() { SalesTaxRates str = new SalesTaxRates(); rate = str.salesRate; // ouch // this should be a method call: // rate = str.getSalesRate("CO"); // do stuff with rate } }

class SalesTaxRates { public float salesRate; // should be private public float adjustedSalesRate; // should be private public float getSalesRate(String region) { salesRate = new DoTaxes().doColorado(); // ouch again // do region-based calculations return adjustedSalesRate; } }

Cohesion
Cohesion is used to indicate the degree to which a
class has a single, well-focused purpose. Coupling is all about how classes interact with each other, on the other hand cohesion focuses on how single class is designed. Higher the cohesiveness of the class, better is the OO design.

Benefits of Higher Cohesion:


Highly cohesive classes are much easier to maintain and less frequently changed. Such classes are more usable than others as they are designed with a well-focused purpose

Low Cohesion
class BudgetReport { void connectToRDBMS(){ } void generateBudgetReport() { } void saveToFile() { } void print() { } }

Highly cohesion
class BudgetReport { Options getReportingOptions() { } void generateBudgetReport(Options o) { } } class ConnectToRDBMS { DBconnection getRDBMS() { } } class PrintStuff { PrintOptions getPrintOptions() { } } class FileSaver { SaveOptions getFileSaveOptions() { } }

Stack and Heap


the various pieces (methods, variables, and objects) of Java programs live in one of two places in memory: the stack or the heap. For now, we're going to worry about only three types of things: instance variables, local variables, and objects: Instance variables and objects live on the heap. Local variables live on the stack.

class Collar { } class Dog { Collar c; // instance variable String name; // instance variable public static void main(String [] args) { Dog d; // local variable: d d = new Dog(); d.go(d); } void go(Dog dog) { // local variable: dog c = new Collar(); dog.setName("Aiko"); } void setName(String dogName) { // local var: dogName

name = dogName; } }

Literal Values for All Primitive Types


'b' // char literal 42 // int literal false // boolean literal 2546789.343 // double literal These are primitive literals:

Integer Literals
There are three ways to represent integer numbers in the Java language: decimal (base 10), octal (base 8), and hexadecimal (base 16).

Octal Literals
Octal integers use only the digits 0 to 7. In Java, you represent an integer in octal form by placing a zero in front of the number, as follows:
class Octal { public static void main(String [] args) { int six = 06; // Equal to decimal 6 int seven = 07; // Equal to decimal 7 int eight = 010; // Equal to decimal 8 int nine = 011; // Equal to decimal 9 System.out.println("Octal 010 = " + eight); } }

Hexadecimal Literals
Hexadecimal (hex for short) numbers are constructed using 16 distinct symbols. we use alphabetic characters to represent these digits. Counting from 0 through 15 in hex looks like this: 0123456789abcdef

class HexTest { public static void main (String [] args) { int x = 0X0001; int y = 0x7fffffff; int z = 0xDeadCafe; System.out.println("x = " + x + " y = " + y + " z ="+z } } x = 1 y = 2147483647 z = -559035650

Primitive Casting
Casts can be implicit or explicit. An implicit cast means you don't have to write code for the cast; the conversion happens automatically. An implicit cast happens when you're doing a widening conversion. In other words, putting a smaller thing (say, a byte) into a bigger container (like an int). The large-value-into-small-container conversion is referred to as narrowing and requires an explicit cast.

int a = 100; long b = a; / / implicit cast float a = 100.001f; int b = (int)a; // Explicit cast

Garbage collection
Garbage collection reclaims or free the memory allocated to objects that are no longer to use. In other OO languages like c++ , the programmer has to free memory that is no longer to required. Failure to free the memory can result in a number of problems. Java automates the garbage collection.

The garbage collector runs as a separate low priority threads. Gc() method invoke the garbage collector. Turn off garbage collector using this statement.java -noasyncgc The program is almost guaranteed to fail due to memory exhaustion.

The finalize method


Java provide a way to clean up a process before the control return to the operating system. protected void finalize() throws Throwable {} Every class inherits the finalize() method from java.lang.Object The method is called by the garbage collector when it determines no more references to the object exist The Object finalize method performs no actions but it may be overridden by any class If overriding finalize() it is good programming practice to use a try-catch-finally statement and to always call super. finalize()