Anda di halaman 1dari 8

OOP is a design philosophy. It stands for Object Oriented Programming.

Object-Oriented Programming (OOP) uses a different set of programming languages than old procedural programming languages (C, Pascal, etc.). Everything in OOP is grouped as self sustainable "objects". Hence, you gain re-usability by means of four main object-oriented programming concepts. 1) Encapsulation: It is the mechanism that binds together code and data in manipulates, and keeps both safe from outside interference and misuse. In short it isolates a particular code and data from all other codes and data. A well-defined interface controls the access to that particular code and data.That idea of encapsulation is to hide how a class does it but to allow requesting what to do. Think of encapsulation as a black box; data is sent to a method, a lot of work goes on using the data, of which you don't know or care about. An output is returned to the caller. That is the process of encapsulation, or information hiding. 2) Inheritance: It is the process by which one object acquires the properties of another object. This supports the hierarchical classification. Without the use of hierarchies, each object would need to define all its characteristics explicitly. However, by use of inheritance, an object need only define those qualities that make it unique within its class. It can inherit its general attributes from its parent. A new sub-class inherits all of the attributes of all of its ancestors. 3) Polymorphism: It is a feature that allows one interface to be used for general class of actions. The specific action is determined by the exact nature of the situation. In general polymorphism means "one interface, multiple methods", This means that it is possible to design a generic interface to a group of related activities. This helps reduce complexity by allowing the same interface to be used to specify a general class of action. It is the compiler's job to select the specific action (that is, method) as it applies to each situation 4)Data Abstraction:Abstraction is an emphasis on the idea, qualities and properties rather than the particulars (a suppression of detail). The importance of abstraction is derived from its ability to hide irrelevant details and from the use of names to reference objects. Abstraction is essential in the construction of programs. It places the emphasis on what an object is or does rather than how it is represented or how it works. Thus, it is the primary means of managing complexity in large programs. Abstraction is the process or result of generalization by reducing the information content of a concept or an observable phenomenon, typically in order to retain only information which is relevant for a particular purpose. For example, abstracting a leather soccer ball to a ball retains only the information on general ball attributes and behaviour. Similarly, abstracting happiness to an emotional state reduces the amount of information conveyed about the emotional state. Computer scientists use abstraction to understand and solve problems and communicate their solutions with the computer in some particular computer language.

Defining Apex Classes In Apex, you can define top-level classes (also called outer classes) as well as inner classes, that is, a class defined within another class. You can only have inner classes one level deep. For example:

public class myOuterClass { // Additional myOuterClass code here class myInnerClass { // myInnerClass code here } } To define a class, specify the following: 1. Access modifiers: o You must use one of the access modifiers (such as public or global) in the declaration of a top-level class. o You do not have to use an access modifier in the declaration of an inner class.

2. Optional definition modifiers (such as virtual, abstract, and so on) 3. Required: The keyword class followed by the name of the class
4. Optional extensions and/or implementations

Use the following syntax for defining classes: private | public | global [virtual | abstract | with sharing | without sharing | (none)] class ClassName [implements InterfaceNameList | (none)] [extends ClassName | (none)] { // The body of the class } The private access modifier declares that this class is only known locally, that is, only by this section of code. This is the default access for inner classesthat is, if you don't specify an access modifier for an inner class, it is considered private. This keyword can only be used with inner classes. The public access modifier declares that this class is visible in your application or namespace. The global access modifier declares that this class is known by all Apex code everywhere. All classes that contain methods defined with the webService keyword must be declared as global. If a method or inner class is declared as global, the outer, top-level class must also be defined as global. The with sharing and without sharing keywords specify the sharing mode for this class. For more information, see Using the with sharing or without sharing Keywords. The virtual definition modifier declares that this class allows extension and overrides. You cannot override a method with the override keyword unless the class has been defined as virtual. The abstract definition modifier declares that this class contains abstract methods, that is, methods that only have their signature declared and no body defined.

Note Classes defined with either virtual or abstract cannot also be defined as global in Developer Edition organizations. They can be defined as global in sandbox organizations. Only private and public classes can be defined as either virtual or abstract in Developer Edition organizations. However, a class defined as global can extend virtual or abstract classes in either Developer Edition organizations or sandboxes.

You cannot add a method to an abstract or virtual class after the class has been uploaded in a Managed - Released package version. For more information about managed packages, see Developing Apex in Managed Packages.

A class can implement multiple interfaces, but only extend one existing class. This restriction means that Apex does not support multiple inheritance. The interface names in the list are separated by commas. For more information about interfaces, see Interfaces and Extending Classes. Interfaces and Extending Classes An interface is like a class in which none of the methods have been implementedthe method signatures are there, but the body of each method is empty. To use an interface, another class must implement it by providing a body for all of the methods contained in the interface. Interfaces can provide a layer of abstraction to your code. They separate the specific implementation of a method from the declaration for that method. This way you can have different implementations of a method based on your specific application. Defining an interface is similar to defining a new class. For example, a company might have two types of purchase orders, ones that come from customers, and others that come from their employees. Both are a type of purchase order. Suppose you needed a method to provide a discount. The amount of the discount can depend on the type of purchase order. You can model the general concept of a purchase order as an interface and have specific implementations for customers and employees. In the following example the focus is only on the discount aspect of a purchase order.

public class PurchaseOrders { // An interface that defines what a purchase order looks like in general public interface PurchaseOrder { // All other functionality excluded Double discount(); } // One implementation of the interface for customers public virtual class CustomerPurchaseOrder implements PurchaseOrder { public virtual Double discount() { return .05; // Flat 5% discount } } // Employee purchase order extends Customer purchase order, but with a // different discount public class EmployeePurchaseOrder extends CustomerPurchaseOrder{ public override Double discount() { return .10; // Its worth it being an employee! 10% discount } } } Note the following about the above example: The interface PurchaseOrder is defined as a general prototype. Methods defined within an interface have no access modifiers and contain just their signature. The CustomerPurchaseOrder class implements this interface; therefore, it must provide a definition for the discount method. As with Java, any class that implements an interface must define all of the methods contained in the interface. The employee version of the purchase order extends the customer version. A class extends another class using the keyword extends. A class can only extend one other class, but it can implement more than one interface.

When you define a new interface, you are defining a new data type. You can use an interface name in any place you can use another data type name. If you define a variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface, or a sub-interface data type. An interface can extend another interface. As with classes, when an interface extends another interface, all the methods and properties of the extended interface are available to the extending interface. See also Classes and Casting. You cannot add a method to an interface after the class has been uploaded in a Managed - Released package version. Salesforce: Polymorphism driven by Apex class inheritance with 9 comments Polywhatsthatnow? Polymorphism is the ability of one type, A, to appear as and be used like another type, B. It is a facet of OOP and can best be described using the good ol example of the Shape class problem (thanks Java!). Lets suppose wed like to create an application that drew a number of shapes on a page. At the time of analysis we know that we want to immediately support circles, but to future-proof our application we need to support the drawing of any shapes. Being Pretty Darn Good Developers(tm) we realise we should create a Shape class that has a single method used to draw itself, and any specific shapes should be derived from this class, and override that method. Make sense? Didnt think so.

In our worked example Ill use colours (Colour = Color my American friends:P) instead of shapes, namely, we have a repeat-tag that will run over a list of classes. Each of these classes have a getColour() method, but certain classes are expected to return specific colours. Thats right we need a list of classes, so they need to be the same class type, but the same method in each must return different values (lets assume without the use of conditional logic statements). Enough dilly-dallying, lets get our code on. To start with well need an interface that dictates the signature required of our classes. view source print? 1 public interface ColourInt { 2 3} Were also going to need a base colour class that implements our interface.. Note the virtual keyword, this allows the class to be inherited, and the method to be overridden. view source print? 1 public virtual class ColourClassBase implements ColourInt{ 2 3 4 5 6} Next well code up some extensions of this base class. Note the extends and override keywords used to inherit the base class, and override its method. view source print? 1 public class Green extends ColourClassBase{ 2 3 4 5 6} view source print? 1 public class Orange extends ColourClassBase{ 2 3 4 5 6} So weve got our backendish logic, now we need a way to expose it to the world. First up the page-controller, view source print? 01 public class ColoursController { 02 public List<ColourClassBase> colours{get;set;} } public virtual override String getColour(){ return 'orange'; } public virtual override String getColour(){ return 'green'; } public virtual String getColour(){ return 'blue'; String getColour();

03 04 05 06 07 08 09 10 11 } And then the page that uses it, view source print? 1 <apex:page controller="ColoursController" showheader="false" standardstylesheets="false"> 2 3 4 5 6 7 8 9 </apex:page> This demos nothing to write home about, but I thought Id put it up so that you know Im not trying to pull a fast one on you. In the real world polymorphism requires a substantial amount of analysis and technical architecturing, but the value becomes apparent when you need to plug another class type (in our case a colour) into your application. That, and you get to feel real smarts-like. <apex:repeat value="{!colours}" var="c"> outputPanel layout="block" style="font-family: Georgia; font-size: 24px"> outputText value="Aweful Colour Combination" style="color:{!c.colour};"/> </apex:outputPanel> </apex:repeat> } colours.add(new ColourClassBase()); colours.add(new Orange()); colours.add(new Green()); public ColoursController(){ colours = new List<ColourClassBase>();

Apex inheritance Extending managed package abstract/virtual classes & interfaces ! In my recent project, I came across a requirement to create a base class in a managed package with child extension packages would extend to add their value to it. Before starting the actual work, I thought of googling about experiences of force.com community members about the same. Interestingly I found one relevant link only i.e. this force.com discussion board question. I became doubtful about this working after reading this post, so thought of giving a quick try, before doing it for our customers. The good news in advance is that this managed package inheritance works. The fixture for this POC experiment is explained below. Fixture for this experiment ! In a top level global class, all 3 types of inheritance forms are created as shown below global class ManagedPackageInheritance { // Virtual Class global virtual class VirtualClass { global virtual void foo () {

System.debug('#Foo from Managed Package !'); } } // Interface global interface IInterface { void bar (); } // Abstract class global abstract class AbstractClass { global abstract void foo() ; } }

Inheriting from Managed package apex classes. The above test fixture was packaged. This package was uploaded as a managed package with namespace prefix abhinav and was installed in some other salesforce DE org. Here we created following child classes implementing/extending all the parent classes/interfaces in the managed package. Everything seems to be working fine, including calling parent class method using super.methodName(). All code shown below : // Extend Virtual class in managed package global class PlayVirtualInheritance extends abhinav.ManagedPackageInheritance.VirtualClass { // override the virtual method global override void foo() { super.foo(); System.debug('#Foo from Target Org !'); } } // Implement interface in managed package global class PlayInterfaceInheritance implements abhinav.ManagedPackageInheritance.IInterface { global void bar() { } } // Extend Abstract class in managed package global class PlayAbstractInheritance extends abhinav.ManagedPackageInheritance.AbstractClass { global override void foo() { System.debug('#Foo from Target Org !'); } }

Please Note ! Inheritance in managed package, works but comes with two very important and strange warning(link to apex doc), shown below : Classes defined with either virtual or abstract cannot also be defined as global in Developer Edition organizations. They can be defined as global in sandbox organizations. Only private and public classes can be defined as either virtual or abstract in Developer Edition organizations. However, a class defined as global can extend virtual or abstract classes in either Developer Edition organizations or sandboxes. o Abhinav: Strange, as I was able to create global classes both virtual & abstract from a DE org. The same was packaged as managed released. Seems this restriction is no more applicable. Salesforce team please confirm ? You cannot add a method to an abstract or virtual class after the class has been uploaded in a Managed - Released package version. For more information about managed packages, see Developing Apex in Managed Packages. o Abhinav: This is very much true, so please do a lot for brain storming before finalizing design of classes and packaging it as managed released.

Apex virtual abstract inheritance versus java inheritance ! Apex is said to be inspired from java. But if we compare the polymorphic behavior specially inheritance, apex inheritance is reciprocal of java inheritance. The difference can be stated in following one line In Java we declare what methods cant be overridden by the child classes VS Apex declares which methods can be overridden ! For example in Java we use final keyword to stop overriding by child classes, this applies to both classes and methods. But in apex to make a class/method inheritable we have to declare it either virtual or abstract. So in Java one declares What you cant extend, and in Apex you declare What you can extend. Cons of Apexs what you can extend philosophy Many times design evolve during coding. You create a bunch of classes and later extend/inherit them to provide more specialization. This is quite easy if you are developing on your own, but if you are integrating with others api via managed packages, then you need to ask a new package release to extend some features. This can happen easily in case if we are distributing utility apis or framework apis written in apex as managed packages, developers might use many of those Apis directly but extension/specialization might be required for some in many cases. Classes should be open to specialization by default, if we want to restrict something from getting specialized we should restrict that only. Apart from What you can extend, apex also requires you to add override keyword before the method you are specializing. Thats again kind of strange, the compiler or run time binding should be smart enough to detect that.

Here is a code sample below that explain the pain in doing a little Object oriented stuff in apex. Java developers know how simple this code will be in JAVA. This example illustrates a simple specialization of ElectricDevice class with Fan. Notice the use of virtual and override Apex Code inheritance Sample public class Polymorphic { // PowerSupply class, // some stuff to setup and initialize a powersupply public class PowerSupply {} // Class must be virtual or abstract // without this one can't extend it public virtual class ElectricDevice { // Child implementations never need to change this. // CAN'T OVERRIDE public void plugToPowerSupply(PowerSupply power) { // Code to plugin to powersupply } // Default device stuff to turn it ON. //Child implementations can change it public virtual void turnOn() {} // Child implementations use this do there specifics, // after Turn ON. public virtual void postTurnOn(){} // Default device stuff to turn it OFF. //Child implementations can change it public virtual void turnOff() {} } public class Fan extends ElectricDevice { // overriden turnOn only public override void turnOn() {} public override void postTurnOn() { // Code to start rotation of fan } }

Java Code inheritance sample This sample is to show, how simple the same code could be in Java. We just used "final" with plugToPowerSupply(), all other stuff is open to inheritance :) public class Polymorphic { // PowerSupply class, // some stuff to setup and initialize a powersupply public class PowerSupply {} // No virtual or abstract public class ElectricDevice { // Child implementations never need to change this. // CAN'T OVERRIDE // NOTE: only "final" added here. public final void plugToPowerSupply(PowerSupply power) { // Code to plugin to powersupply } // Default device stuff to turn it ON. //Child implementations can change it public void turnOn() {} // Child implementations use this do there specifics, // after Turn ON. public void postTurnOn(){} // Default device stuff to turn it OFF. //Child implementations can change it public void turnOff() {} } public class Fan extends ElectricDevice { // overriden turnOn only public void turnOn() {} public void postTurnOn() { // Code to start rotation of fan } } } Though Apex is a great language and is adding cool new features. But I wish the can really use java style inheritance.

Anda mungkin juga menyukai