OBJECT ORIENTED PROGRAMMING Programming model where programs are developed around objects and data rather than

actions and logics. In OOPs, every real life object has properties and behavior. This feature is achieved in java through the class and object creation. CLASS A class defines the properties and behavior (instance variables and methods) that is shared by all its objects. It is a blue print for the creation of objects. OBJECT Object is the basic entity of OOP language. Class itself does nothing but the real functionality is achieved through their objects. Object is an instance of the class. It takes the properties (variables) and uses the behavior (methods) defined in the class. Three key characteristics of objects  The object‘s behavior: The behavior of an object is defined by the methods that you can call.  The object‘s state: Each object stores information about what it currently looks like. This is the object‘s state. A change in the state of an object must be a consequence of method calls.  The object‘s identity: For example, in an order-processing system, two orders are distinct even if they request identical items. Relationships between Classes  Dependence (―uses–a‖): For example, the Order class uses the Account class because Order objects need to access Account objects to check for credit status.  Aggregation (―has–a‖): For example, an Order object contains Item objects. Containment means that objects of class A contain objects of class B.  Inheritance (―is–a‖): For example, if class A extends class B, class A inherits methods from class B but has more capabilities. ENCAPSULATION Encapsulation is the process of binding together the methods and data variables as a single entity. This keeps both the data and functionality code safe from the outside world. It hides the data (instance fields) within the class and makes it available only through the methods. Java provides different accessibility scopes (public, protected, private, default) to hide the data from outside. For example, we can create a class "Check" which has a variable "amount" to store the current amount. Now to manipulate this variable we can create methods. For example to set the value of amount create setAmount() method and to get the value of amount create getAmount() method.    Keep instance variables protected (with an access modifier, often private). Make public accessor methods, and force calling code to use those methods rather than directly accessing the instance variable. For the methods, use the JavaBeans naming convention of set<someProperty> and get<someProperty>.

There is an important difference between objects and object variables. For example, the statement Date deadline; // defines an object variable

defines an object variable, deadline, that can refer to objects of type Date. Then you must first initialize the deadline variable. You have two choices. Of course, you can initialize the variable with a newly constructed object: deadline = new Date(); or you can set the variable to refer to an existing object: deadline = birthday; Now both variables refer to the same object. In Java, the value of any object variable is a reference to an object that is stored elsewhere. The return value of the new operator is also a reference. A statement such as Date deadline = new Date(); has two parts. The expression new Date() makes an object of type Date, and its value is a reference to that newly created object. That reference is then stored in the deadline variable.

JAVABEANS They are Java classes that have properties. For our purposes, think of properties as private instance variables. Since they‘re private, the only way they can be accessed from outside of their class is through methods in the class. The methods that change a property's value are called SETTER METHODS (mutators), and the methods that retrieve a property's value are called GETTER METHODS (accessors). JavaBean spec supports events, which allow components to notify each other when something happens. The objects that receive the information that an event occurred are called LISTENERS. Objects are always created on heap, whereas references are stored on stack. Primitive data types are always passed ‗by value‘; the value is copied into the parameter. Objects are always passed as references; the reference is copied, not the object.

CLASS DECLARATIONS AND MODIFIERS Access modifiers: public, protected, private. Non-access modifiers (including strictfp, final, and abstract) NOTE: A class can be declared with only public or default access. While the class members can use all four. DEFAULT ACCESS Think of default access as package-level access, because a class with default access can be seen only by classes within the same package. For example, if class A and class B are in different packages, and class A has default access, class B won't be able to create an instance of class A, or even declare a variable or return type of class A.In fact, class B has to pretend that class A doesn't even exist, or the compiler will complain. Look at the following source file: package cert; class Beverage { } Now look at the second source file: packageexam.stuff; importcert.Beverage; class Tea extends Beverage { } As you can see, the superclass (Beverage) is in a different package from the subclass (Tea). The import statement at the top of the Tea file is trying to import the Beverage class. The Beverage file compiles fine, but Tea won't compile because its superclass, Beverage, has default access and is in a different package. You can do one of two things to make this work. You could put both classes in the same package, or you could declare Beverage as public PUBLIC ACCESS A class declaration with the public keyword gives all classes from all packages access to the public class. But yes, if a public class you're trying to use is in a different package from the class you're writing, you'll still need to import the public class. In the example from the preceding section, to make the code work, we need to add the keyword public in front of the superclass (Beverage) declaration, as follows: package cert; public class Beverage { } Declare Class Members 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. PRIVATE MEMBERS Members marked private can't be accessed by code in any class other than the class in which the private member was declared. NOTE: A subclass cannot inherit a private method. A method marked private cannot be overridden. PROTECTED AND DEFAULT MEMBERS 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. package certification; public class Parent { protected int x = 9; }

// protected access

package other; import certification.Parent; class Child extends Parent { public void testIt() { System.out.println("x is " + x); Parent p = new Parent(); System.out.println("X in parent is " + p.x); } }

// Different package

// No problem; Child inherits x // Can we access x using the p reference? // Compiler error!

So subclasses outside the package can inherit a protected member. Finally, we've seen that subclasses outside the package can't use a superclass reference to access a protected member. For a subclass outside the package, the protected member can be accessed only through inheritance. But once the subclass-outside-the-package inherits the protected member, that member (as inherited by the subclass) becomes private to any code outside the subclass, with the exception of subclasses of the subclass. So if class Neighbor instantiates a Child object, then even if class Neighbor is in the same package as class Child, class Neighbor won't have access to the Child's inherited (but protected) variable x. Just remember that default members are visible to subclasses only if those subclasses are in the same package as the superclass. Can access modifiers be applied to local variables? NO! In fact, there is only one modifier that can ever be applied to local variables—final.

ABSTRACT CLASSES  An abstract class can never be instantiated. Its sole purpose is to be extended (subclassed).  If even a single method is abstract, the whole class must be declared abstract. You can, however, put nonabstract methods in an abstract class.  You can't mark a class as both abstract and final. An abstract class must be subclassed, whereas a final class must not be subclassed.  The methods marked abstract end in a semicolon rather than curly braces. abstract class Car { private double price; private String model; public abstract void goFast(); public abstract void goUpHill(); // Additional, important, and serious code goes here } ABSTRACT METHODS An abstract method is a method that's been declared (as abstract) but not implemented. Any class that extends an abstract class must implement all abstract methods of the superclass, unless the subclass is also abstract. Concrete just means nonabstract, so if you have an abstract class extending another abstract class, the abstract subclass doesn't need to provide implementations for the inherited abstract methods. Sooner or later, though, somebody's going to make a nonabstract subclass (in other words, a class that can be instantiated), and that subclass will have to implement all the abstract methods from up the inheritance tree. A method can never, ever, ever be marked as both abstract and final, or both abstract and private. Abstract methods must be implemented (which essentially means overridden by a subclass) whereas final and private methods cannot ever be overridden by a subclass. The abstract modifier can never be combined with the static modifier.

The following code won‘t compile: public abstract class A { abstract void foo(); } class B extends A { void foo(int I) { } } Class B won't compile because it doesn't implement the inherited abstract method foo(). Although the foo(int I) method in class B might appear to be an implementation of the superclass' abstract method, it is simply an overloaded method, so it doesn't fulfill the requirements for implementing the superclass' abstract method.

DECLARE INTERFACE While an abstract class can define both abstract and non-abstract methods, an interface can have only abstract methods.     All interface methods are implicitly public and abstract. All variables defined in an interface must be public, static, and final. In other words, interfaces can declare only constants, not instance variables. An interface cannot implement another interface or class. An interface cannot extend anything but another interface (an interface can extend one or more other interfaces)

public interface Bounceable { int BAR = 42; void bounce(); voidsetBounceFactor(int bf); }

interface Foo { int BAR = 42; void go(); } class Zap implements Foo { public void go() { BAR = 27; } } You can't change the value of a constant! Once the value has been assigned, the value can never be modified. The assignment happens in the interface itself (where the constant is declared), so the implementing class can access it and use it, but as a read-only value. So the BAR = 27 assignment will not compile.

FINAL CLASSES When used in a class declaration, the final keyword means the class can't be subclassed. In other words, no other class can ever extend (inherit from) a final class, and any attempts to do so will give you a compiler error. You should make a final class only if you need an absolute guarantee that none of the methods in that class will ever be overridden. You'll notice many classes in the Java core libraries are final. For example, the String class cannot be subclassed. 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. A typical final method declaration looks like this: classSuperClass{ 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: classSubClass extends SuperClass{ public void showSample() { // Try to override the final superclass method System.out.println("Another thing."); } }

FINAL VARIABLES For primitives, this means that once the variable is assigned a value, the value can't be altered. For example, if you assign 10 to the int variable x, then x is going to stay 10, forever. A reference variable marked final can't ever be reassigned to refer to a different object. The data within the object can be modified, but you can't modify the reference variable to make it refer to a different object

STATIC VARIABLES AND METHODS The static modifier is used to create variables and methods that will exist independently of any instances created for the class. All static members exist before you ever make a new instance of a class, and there will be only one copy of a static member regardless of the number of instances of that class.

Variable Declarations INSTANCE VARIABLES Instance variables are defined inside the class, but outside of any method, and are only initialized when the class is instantiated. Instance variables are the fields that belong to each unique object. For example, the following code defines instance variables for the name, title, and manager for employee objects: class Employee { // private String name; private String title, private String manager; // other code goes here including access methods for private fields } LOCAL VARIABLES  Local variables are variables declared within a method. That means the variable is not just initialized within the method, but also declared within the method.  Just as the local variable starts its life inside the method, it's also destroyed when the method has completed. A local variable can't be referenced in any code outside the method in which it's declared.  Local variables are always on the stack, not the heap. Before a local variable can be used, it must be initialized with a value. classTestServer { public void logIn() { int count = 10; } } It is possible to declare a local variable with the same name as an instance variable. It's known as shadowing. define fields (instance variables) for employee instances

The following (wrong) code is trying to set an instance variable's value using a parameter: class Foo { int size = 27; public void setSize(int size) { size = size; } }

// ??? which size equals which size???

To resolve the naming collision, use the keyword this. The keyword ‘this’ always, always, always refers to the object which is invoking the member function. The following code shows this in action: class Foo { int size = 27; public void setSize(int size) { this.size = size; // this.size means the current object's instance variable, size. The size on the right is the parameter } }

INHERITANCE Two most common reasons to use inheritance are ■ To promote code reuse classGameShape { public void displayShape() { System.out.println("displaying shape"); } // more code } classPlayerPiece extends GameShape { public void movePiece() { System.out.println("moving game piece"); } // more code } public class TestShapes { public static void main (String[] args) { PlayerPiece shape = new PlayerPiece(); shape.displayShape(); shape.movePiece(); } } Outputs: displaying shape moving game piece ■To use polymorphism Imagine we now have two specialized subclasses that extend the more generic GameShape class, PlayerPiece and TilePiece: classGameShape { public void displayShape() { System.out.println("displaying shape"); } // more code } classPlayerPiece extends GameShape { public void movePiece() { System.out.println("moving game piece"); } // more code } classTilePiece extends GameShape { public void getAdjacent() { System.out.println("getting adjacent tiles"); } // more code } Now imagine a test class has a method with a declared argument type of GameShape, which means it can take any kind of GameShape. In other words, any subclass of GameShape can be passed to a method with an argument of type GameShape. This code public class TestShapes { public static void main (String[] args) { PlayerPiece player = new PlayerPiece(); TilePiece tile = new TilePiece(); doShapes(player);

doShape s(tile); } public static void doShapes(GameShape shape) { shape.displayShape(); } } Outputs: displaying shape displaying shape The key point is that the doShapes() method is declared with a GameShape argument but can be passed any subtype (in this example, a subclass) of GameShape. IS-A Relationship You express the IS-A relationship in Java through the keywords extends (for class inheritance) and implements (for interface implementation). public class Vehicle { ... } public class Car extends Vehicle { ... } public class Subaru extends Car { ... } "Subaru IS-A Vehicle" because a class is said to be "a type of" anything further up in its inheritance tree. HAS-A Relationship Class A HAS-A B if code in class A has a reference to an instance of class B. For example, you can say the following, A Horse IS-A Animal. A Horse HAS-A Halter. The code might look like this: public class Animal { } public class Horse extends Animal { private Halter myHalter; } POLYMORPHISM      A reference variable can be of only one type, and once declared, that type can never be changed A reference is a variable, so it can be reassigned to other objects, (unless the reference is declared final). A reference variable's type determines the methods that can be invoked on the object the variable is referencing. A reference variable can refer to any object of the same type as the declared reference, or—this is the big one—it can refer to any subtype of the declared type! A reference variable can be declared as a class type or an interface type. If the variable is declared as an interface type, it can reference any object of any class that implements the interface.

OVERRIDDEN METHODS When you extend a class and write a method in the derived class which is exactly similar to the one present in the base class, it is termed as overriding. The key benefit of overriding is the ability to define behavior that's specific to a particular subclass type. The rules for overriding a method are as follows:  The argument list must exactly match that of the overridden method. If they don't match, you can end up with an overloaded method you didn't intend.

  

The return type must be the same as, or a subtype of, the return type declared in the original overridden method in the superclass. You cannot override a method marked final or static. If a method can't be inherited, you cannot override it.

Let us look at an example. class Animal{ public void move(){ System.out.println("Animals can move"); } } class Dog extends Animal{ public void move(){ System.out.println("Dogs can walk and run"); } } public class TestDog{ public static void main(String args[]){ Animal a = new Animal(); // Animal reference and object Animal b = new Dog(); // Animal reference but Dog object a.move();// runs the method in Animal class b.move();//Runs the method in Dog class } } This would produce following result: Animals can move Dogs can walk and run In the above example you can see that the even though b is a type of Animal it runs the move method in the Dog class. The reason for this is: In compile time the check is made on the reference type. However in the runtime JVM figures out the object type and would run the method that belongs to that particular object. Therefore in the above example, the program will compile properly since Animal class has the method move. Then at the runtime it runs the method specific for that object. Consider the following example: class Animal{ public void move(){ System.out.println("Animals can move"); } }

class Dog extends Animal{ public void move(){ System.out.println("Dogs can walk and run"); } public void bark(){ System.out.println("Dogs can bark"); } } public class TestDog{ public static void main(String args[]){ Animal a = new Animal(); // Animal reference and object Animal b = new Dog(); // Animal reference but Dog object a.move(); // runs the method in Animal class b.move(); //Runs the method in Dog class b.bark(); } } This program will throw a compile time error since b's reference type Animal doesn't have a method by the name of bark. Now let's modify the polymorphic example we saw earlier in this section. Here the overriding method is not able to fulfill the contract of the superclass:

INVOKING A SUPERCLASS VERSION OF AN OVERRIDDEN METHOD class Animal{ public void move(){ System.out.println("Animals can move"); } } class Dog extends Animal{ public void move(){ super.move(); // invokes the super class method System.out.println("Dogs can walk and run"); } } public class TestDog{ public static void main(String args[]){ Animal b = new Dog(); b.move(); } } This would produce following result: Animals can move Dogs can walk and run

// Animal reference but Dog object //Runs the method in Dog class

OVERLOADED METHODS Overloaded methods let you reuse the same method name in a class, but with different arguments (and optionally, a different return type). class Animal { } class Horse extends Animal { } classUseAnimals { public void doStuff(Animal a) { System.out.println("In the Animal version"); } public void doStuff(Horse h) { System.out.println("In the Horse version"); } public static void main (String [] args) { UseAnimalsua = new UseAnimals(); Animal animalObj = new Animal(); Horse horseObj = new Horse(); ua.doStuff(animalObj); ua.doStuff(horseObj); } } The output is what you expect: in the Animal version in the Horse version But what if you use an Animal reference to a Horse object? Animal animalRefToHorse = new Horse(); ua.doStuff(animalRefToHorse); The preceding code would actually print: in the Animal version Just remember, the reference type (not the object type) determines which overloaded method is invoked! To summarize, which overridden version of the method to call (in other words, from which class in the inheritance tree) is decided at runtime based on object type, but which overloaded version of the method to call is based on the reference type of the argument passed at compile time.

POLYMORPHISM IN OVERLOADED AND OVERRIDDEN METHODS Polymorphism does come into play when the decision is about which overridden version of a method is called. But sometimes, a method is both overloaded and overridden. Imagine the Animal and Horse classes look like this: public class Animal { public void eat() { System.out.println("Generic Animal Eating Generically"); } } public class Horse extends Animal { public void eat() { System.out.println("Horse eating hay "); } public void eat(String s) { System.out.println("Horse eating " + s); } }

CONSTRUCTOR AND INITIATION        A constructor is a special method whose purpose is to construct and initialize objects. Every class, including abstract classes, MUST have a constructor. Their names must exactly match the class name. A constructor is always called with the new operator. A constructor without input parameter is default constructor. A constructor can't ever, ever, ever, have a return type, not even void. Constructors can't be marked static (they are after all associated with object instantiation), they can't be marked final or abstract (because they can't be overridden).

class Foo { int size; String name; Foo(String name, int size) { this.name = name; this.size = size; } } The following will fail to compile: Foo f = new Foo(); but the following will compile: Foo f = new Foo("Fred", 43);    The default constructor has the same access modifier as the class. The default constructor has no arguments. The default constructor includes a no-arg call to the super constructor (super()). // Won't compile, no matching constructor

What happens if the super constructor has arguments? class Clothing { Clothing(String s) { } } classTShirt extends Clothing { // Constructor identical to compiler-supplied default constructor TShirt() { super(); } } // Won't work! It should be super(“button”); // Invokes a no-argClothing() constructor, but there isn't one!

Constructors are never inherited. They aren't methods. They can't be overridden, but can be overloaded. The only way a constructor can be invoked is from within another constructor. In other words, you can't write code that actually calls a constructor as follows: class Horse { Horse() { } // constructor

void doStuff() { Horse(); } } OVERLOADED CONSTRUCTORS

// calling the constructor - illegal!

this() always means a call to another constructor in the same class. The first line in a constructor must be a call to super() or a call to this(). A constructor can never have both a call to super() and a call to this().

STATIC VARIABLES AND METHODS Variables and methods marked static belong to the class, rather than to any particular instance. The following code declares and uses a static counter variable: class Frog { static intfrogCount = 0; // Declare and initializestatic variable public Frog() { frogCount += 1; // Modify the value in the constructor } public static void main (String [] args) { new Frog(); new Frog(); new Frog(); System.out.println("Frog count is now " + frogCount); } } When this code executes, three Frog instances are created in main(), and the result is Frog count is now 3 Now imagine what would happen if frogCount were an instance variable (in other words, nonstatic): class Frog { int frogCount = 0; // Declare and initialize instance variable public Frog() { frogCount += 1; // Modify the value in the constructor } public static void main (String [] args) { new Frog(); new Frog(); new Frog(); System.out.println("Frog count is now " + frogCount); } } The JVM doesn't know which Frog object's frogCount you're trying to access.The problem is that main() is itself a static method, and a static method can't access a nonstatic (instance) variable, because there is no instance! The same applies to instance methods; a static method can't directly invoke a nonstatic method. To access a static method (or static variable), use the dot operator on the class name. class Frog { static intfrogCount = 0; public Frog() { frogCount += 1; } } // Declare and initialize static variable // Modify the value in the constructor

classTestFrog { public static void main (String [] args) { new Frog(); new Frog(); new Frog(); System.out.print("frogCount:"+Frog.frogCount); } }

//Access static variable

Finally, remember that static methods can't be overridden! class Animal { static void doStuff() { System.out.print("a "); } } class Dog extends Animal { static void doStuff() { // it's a redefinition, not an override System.out.print("d "); } public static void main(String [] args) { Animal [] a = {new Animal(), new Dog(), new Animal()}; for(int x = 0; x <a.length; x++) a[x].doStuff(); // invoke the static method } } Running this code produces the output: aaa

Sign up to vote on this title
UsefulNot useful