Shri PankajClasses1 what is a class and an object? A class is a user-defined data type, which has a state (its representation or internal data) andsome operations (its behavior or its methods). An object is an instance of a class, or a variable of thedata type defined by the class. Objects are actual entities. When the program runs, objects take upsome memory for their internal representation. The relationship between object and class is thesame as the one between variable and type. An Object consists of method, and in many cases, properties, and events, properties represent thedata contained in the object.2. What are the visibility options for class members? What is the difference betweenthem? Visibility determines where and how a member can be accessed, with private representing theleast accessibility, protected representing an intermediate level of accessibility, and public,published, and automated representing the greatest accessibility. You can increase the visibility of a member in a descendant class by redeclaring it, but youcannot decrease its visibility.3. Is it possible to use private member of class in some other class? If Classes are declaredin the same unit? ------ Yes4. Can we change the visibility of members in the descendent classes? ----- No5. Can I have a class with more than one constructor? ------ Yes6. Class function. Why we use it? Its important to know how these functions are called when you create an object, because youcan hook in two different steps. As you call a constructor, Delphi invokes the New Instance virtualclass function, defined in TObject. Because this is a virtual function, you can modify the memorymanager for a specific class by overriding it. To perform the memory allocation, however, NewInstance typically ends up calling the GetMem function of the active memory manager, whichprovides you with your second chance to customize the standard behavior.7. What is use of inheritance? We often need to use a slightly different version of an existing class that we have written or thatsomeone has given to us. For example, you might need to add a new method or slightly change anexisting one. You can do this easily by modifying the original code, unless you want to be able to usethe two different versions of the class in different circumstances. A typical alternative is to make a copy of the original type definition, change its code to supportthe new features, and give a new name to the resulting class. This might work, but it also mightcreate problems: In duplicating the code you also duplicate the bugs; and if you want to add a newfeature, you’ll need to add it two or more times, depending on the number of copies of the originalcode you’ve made. This approach results in two completely different data types, so the compilercannot help you take advantage of the similarities between the two types. To solve these kinds of problems in expressing similarities between classes, Object Pascalallows you to define a new class directly from an existing one. This technique is known asinheritance (or subclassing) and is one of the fundamental elements of object-orientedprogramming languages. To inherit from an existing class, you only need to indicate that class atthe beginning of the declaration of the subclass.
8. We have two classes. A and B = Class(A). Now you have created one variable of for eachclass. Now can you say B1 = A1. -------- No.9. What do you by Abstract Classes? When we will never want to instantiate objects of a base class, we call it an abstract class. Such aclass exists only to act as a parent of derived classes that will be used to instantiate objects. It mayalso provide an interface for the class hierarchy.10. Can you make an object of abstract classes? ---------- (Yes, Warning)11. Can we define an abstract method without a virtual keyword? --------- (No)12. Is it compulsory to define all the abstract method in the descendent classes? ----- (Yes)Interface1. Can we declare variables in interface? ----- (No, Only Properties and method are allowed)2. Can we declare read-only property? -------- (Yes)3. Can we have private, published or protected method? ------ (No, Only public allowed)Constructor 1. What do you mean by constructor? As I’ve mentioned, to allocate the memory for the object, we call the Create method.This is a constructor, a special method that you can apply to a class to allocate memory for aninstance of that class. The instance is returned by the constructor and can be assigned to a variablefor storing the object and using it later on. The default TObject. Create constructor initializes all thedata of the new instance to zero. If you want your instance data to start out with a nonzero value, then you need to write a customconstructor to do that. Although you can use any name for a constructor, you should stick to the standard name, Create.Although the declaration specifies no return value, a constructor returns a reference to the object itcreates or is called in.2. Can we overload constructor? ---- ( No)3. Can we define it as a virtual function? What is the use? ------ (Yes)4. How we can create an object dynamically?Virtual1. What is virtual function? Virtual means existing in appearance but not in reality. When virtual functions are used, aprogram that appears to be calling a function of one class may in reality be calling a function of adifferent class. Why are needed ------Suppose you have a number of objects of different classes butyou want to put them all in an array and perform a particular operation on then using the samefunction call. A more complicated and more flexible, dispatch mechanism than static method. Can be redefinedin descendent classes, but still be called in the ancestor class and object where the method isdefining looks up the address at runtime.
2. What is Dynamic function? Virtual and dynamic methods, unlike static methods, can be overridden in descendant classes.When an overridden method is called, the actual (runtime) type of the class or object used in themethod call--not the declared type of the variable--determines which implementation to activate. To override a method, redeclare it with the override directive. An override declaration must matchthe ancestor declaration in the order and type of its parameters and in its result type (if any).3. You have two classes. A and B. B = Class (A); One virtual function let say Test isdeclared here. Now if you have declared two object of class A Var A1, A2: A; Begin A1 := A.Create; A2 :=B.Create ; A1.test; // Will call a test A2.test; // Will call b.test end;What will be output?5. Can we overload a virtual function? ---- (Yes) 6. How can be override virtual function? You can override virtual methods in subclasses by using the override directive. If you don’t usevirtual methods, you can still provide a new implementation in a subclass by redeclaring theinterface type in the subclass, rebinding the interface methods to new versions of the static methods.At first sight, using virtual methods to implement interfaces seems to allow for smoother coding insubclasses, but both approaches are equally powerful and flexible.7. Suppose you have two classes. Class B is inherited from class A. In class a you haveone virtual function let’s say Draw. Can you declare the same virtual function in class B. [Warning] Unit1.pas (36). Method ‘draw’ hides virtual method of base type ‘A’.7. What is the solution if you still want to declare this function is class B. Use Reintroduce Type T1-class(TObject) Procedure Test (I: Integer); Overload; virtual; End; T2 = class (T1) Procedure Test (I: Integer); Reintroduce; Overload; End; ---- SomeObject: = T2.Create; SomeObject.Test(‘Hello’); /// Calls T2.Test SomeObject.Test(7); ///Calls T1.TestReintroduce: To avoid this message and to instruct the compiler more precisely on your intentions,you can use the reintroduce directive. Reintroduce directive suppresses compiler warring abouthiding previously declared virtual method.
Overload1. What is Overloading? Object Pascal supports overloaded functions and methods: you can have multiple methods withthe same name, provided that the parameters are different. By checking the parameters, thecompiler can determine which of the versions of the routine you want to call. There are two basic rules: - Each version of the method must be followed by the overload keyword. - The differences must be in the number or type of the parameters or both. The return typecannot be used to distinguish between two methods. Overloading can be applied to global functions and procedures and to methods of a class.2. What conditions must be satisfied, in order to declare an overloaded function?3. Can we use default parameter in overloading? ---- YesPolymorphism: Polymorphism means you can write a call to a method, applying it to a variable, but whichmethod Delphi actually calls depends on the type of the object the variable relates to. Delphi cannotdetermine until run time the actual class of the object the variable refers to, because of the type-compatibility rule discussed in the previous section.Late Binding: This means that a method call is resolved by the compiler and linker, which replace the requestwith a call to the specific memory location where the function or procedure resides. (This is knownas the address of the function.) OOP languages allow the use of another form of binding, known asdynamic or late binding. In this case, the actual address of the method to be called is determinedat run time based on the type of the instance used to make the call.Encapsulation: A class can have any amount of data and any number of methods. However, for a good objectoriented approach, data should be hidden, or encapsulated, inside the class using it. Using methodsto access the internal representation of an object limits the risk of generating erroneous situations,as the methods can check whether the date is valid and refuse to modify the new value if it is not.Encapsulation is important because it allows the class writer to modify the internal representationin a future version. The concept of encapsulation is often indicated by the idea of a “black box,” where you don’t knowabout the internals: You only know how to interface with it or how to use it regardless of its internalstructure. The “how to use” portion, called the class interface, allows other parts of a program toaccess and use the objects of that class. However, when you use the objects, most of their code ishidden. You seldom know what internal data the object has, and you usually have no way to accessthe data directly.
Property1. Property / Public. Why we use it? Property: A property, like a field, defines an attribute of an object. But while a field is merely astorage location whose contents can be examined and changed, a property associates specific actionswith reading or modifying its data. Properties provide control over access to an objects attributes,and they allow attributes to be computed. Properties are defined by their access specifies. Unlike fields, properties cannot be passed as varparameters, nor can the @ operator be applied to a property. The reason is that a property doesntnecessarily exist in memory. It could, for instance, have a read method that retrieves a value from adatabase or generates a random value. Private, protected, and public members: A private member is invisible outside of the unit or program where its class is declared. Inother words, a private method cannot be called from another module, and a private field or propertycannot be read or written to from another module. By placing related class declarations in the samemodule, you can give the classes’ access to one anothers private members without making thosemembers more widely accessible.A protected member is visible anywhere in the module where its class is declared and from anydescendant class, regardless of the module where the descendant class appears. A protected methodcan be called, and a protected field or property read or written to, from the definition of any methodbelonging to a class that descends from the one where the protected member is declared. Membersthat are intended for use only in the implementation of derived classes are usually protected.A public member is visible wherever its class can be referenced.2. Read only Property? The write directive of a property can be omitted, making it a read-only property. The compiler willissue an error if you try to change it. You can also omit the read directive and define a write-onlyproperty, but that doesn’t make much sense and is used infrequently.3. Can we overload property? ---- (No)4. Can we override a property? ----- (Declare the property with specifying the type )VCL2. Who is the ultimate of all VCL objects and components? -------- (Tobject)3. For creating a new component which is visible to the user at runtime which classshould be use as the base class? ----- (Tobject, Tcontrol or TComponent) (Tcontrol)4. I have a from and on this form I have two buttons and one panel. On the panel I haveone more button. Form1.Controlcount; Form1.Componentcount? (Controlcount gives parent, component count gives owner) Componentcount = 4; Controlcount = 3(Two buttons and one panel). Panel1.controlcount =1; Panel1.componentcount =0 (even though buttons is placed on the panel,owner is form1)
Forms2. Can we change owner at runtime? ------ No Change.3. You have tow forms on form1 you have a button. How can you move it to form2? --- Yes4. After this suppose you have closed Form1. What will be effect on button1? When youclose Form2 will it generate any error? ---5. Can we delete a component introduced in the base form? ---- No delete in inherited form.6. Can we edit DFM manually? ----- Yes.Exception HandlingThe benefit of an exception handling system as used in Delphi is that applications can, despite of arun time error, keep running without crashing.The application can close normally and data can be saved.Delphi generates an exception when a runtime error occurs.This exception can be solved in the code. (You have to program that yourself of course)When the code does nothing the error ’floats’ up to the calling code.This goes on and on until there is no code anymore, at that time Delphi will try to solve the problem.The systemThe next keywords belong to the exception handling system:try is the beginning of the protected code.except is the end of this codefinally is code that must be executed, even if an error occurs.raise give you the possibility to generate an exception manually.1. Can we have Try, Except and finally block together? --- No. Try – Finally:This block guaranties that the code after finally will be executed even if a runtime error shows up.This block is important for resource protection. For example for freeing of objects, like a form.Sometimes you want to ensure that specific parts of an operation are completed, whether or not theoperation is interrupted by an exception. For example, when a routine acquires control of a resource,it is often important that the resource be released, regardless of whether the routine terminatesnormally. In these situations, you can use a try...finally statement. Try- Except:When the code in the try part doesnt generate an error then the code in de except part will never beused.If an error occurs the program will continue after except.The error can be determined and solved.The user will not see the by Delphi generated exception. (That one is destroyed)So excepts allows a solution for the error and a friendly message to the user.The exception handling block starts with the except keyword and ends with the keyword end. Thesetwo keywords are actually part of the same statement as the try block. That is, both the try blockand the exception handling block are considered part of a single try...except statement.
Raise:Raise can be used to re-raise an exception. The exception can be handled evenly.You can also use raise to generate exceptions manually: raise EDiveByZero.Create (Divide byzero);2. Can we use keyword raise in Try Block? ---- Yes.3. What is RTTI? Runtime type information (RTTI) is generated for published members. RTTI allows anapplication to query the fields and properties of an object dynamically and to locate its methods.RTTI is used to access the values of properties when saving and loading form files, to displayproperties in the Object Inspector, and to associate specific methods (called event handlers) withspecific properties (called events). The TPersistent class defined in the Classes unit of the component library is declared in thestate, so any class derived from TPersistent will have RTTI generated for its published sections. Thecomponent library uses the runtime type information generated for published sections to access thevalues of a components properties when saving or loading form files. Furthermore, the IDE uses acomponents runtime type information to determine the list of properties to show in the ObjectInspector.