CLASSES AND OBJECTS. BASIC PRINCIPLES OF OOP 1. Data Encapsulation 2. Data Hiding 3. Inheritance 4. Polymorphism DEFINING A CLASS

Size: px
Start display at page:

Download "CLASSES AND OBJECTS. BASIC PRINCIPLES OF OOP 1. Data Encapsulation 2. Data Hiding 3. Inheritance 4. Polymorphism DEFINING A CLASS"

Transcription

1 CLASSES AND OBJECTS 1 BASIC PRINCIPLES OF OOP 1. Data Encapsulation 2. Data Hiding 3. Inheritance 4. Polymorphism DEFINING A CLASS class classname [variable declaration;] [methods declaration;] class classname 2 1

2 CATEGORIES OF CLASS MEMBERS Class Members Instance Members Static Members Data Members Function Members Fields Constants Events Methods Properties Indexers Construct or Destructor 3 MEMBERS ACCESS MODIFIERS Modifier private public protected internal protected internal Accessibility Control Member is accessible only within the class containing the member Member is accessible from anywhere outside the class as well. It is also accessible in derived classes. Member is visible only to its own class and its derived classes. Member is available within the assembly or component that is being created but not to the clients of that component Available in the containing program or assembly and in the derived classes. 4 2

3 // APPLICATION OF CLASSES AND OBJECTS class Rectangle public int length, width; public void GetData(int x,int y) length = x; width = y; public int RectArea () int area = length * width; return (area); class RectArea int area1,area2; Rectangle rect1 = new Rectangle (); Rectangle rect2 = new Rectangle (); rect1.length = 15; rect1.width = 10; area1 = rect1.length * rect1.width ; rect2.getdata (20,10); area2 = rect2.rectarea (); Console.WriteLine ("Area1 = " + area1); Console.WriteLine ("Area2 = " + area2); 5 // APPLICATION OF CONSTRUCTORS class Rectangle public int length,width; public Rectangle(int x,int y) //Defining Constructor length = x; width = y; public int RectArea() return (length * width); class RectangleArea Rectangle rect1 = new Rectangle (15,10); int area1 = rect1.rectarea (); Console.WriteLine ("Area1 = " +area1); 6 3

4 // APPLICATION OF OVERLOADED CONSTRUCTORS class Room public double length; public double breadth; public Room(double x,double y) length = x; breadth = y; public Room(double x) length = breadth = x; public double Area() return (length * breadth); class MainRoom Room room1 = new Room (25.0,15.0); Room room2 = new Room (20.0); Console.WriteLine ("The Room One is:"+room1.area ()); Console.WriteLine ("The Room Two is:"+room2.area ()); 7 Static Members Static methods have several restrictions 1. They can only call other static methods. 2. They can only access static data. 3. They cannot refer to this or base in any way. 8 4

5 //Defining and using static members class Mathoperation public static float mul (float x,float y) return x*y; public static float divide(float x,float y) return x/y; class MathApplication float a = Mathoperation.mul (4.0F,5.0F); float b = Mathoperation.divide (a,2.0f); Console.WriteLine ("b: " + b); 9 Static Constructor 1. It is usually used to assign initial values to static data members 2. It cannot have any parameters. 3. There is no access modifier on static constructors. 4. A Class can have only one static constructor. 10 5

6 //STATIC CONSTRUCTOR class Mathoperation static int x,y; static Mathoperation() x = 23; y = 45; public void display () Console.WriteLine ("The X Value is: " + x); Console.WriteLine ("The Y Value is: " + y); class staticmathoperation Mathoperation m = new Mathoperation (); m.display (); 11 //PRIVATE CONSTRUCTOR class AClass uint afield; private AClass() afield = 45; System.Console.WriteLine(aField); class Inner static void Main() new AClass(); 12 6

7 //COPY CONSTRUCTOR class Customer private string name; public Customer(string name) this.name = name; public Customer(Customer customer) this.name = customer.name; public string Name get return name; set name = value; class MainClass static void Main() Customer customer = new Customer("Paul"); Customer customercopy = new Customer(customer); customer.name = "Sam"; System.Console.WriteLine("The new customer's name is 0", customercopy.name); 13 Destructors A destructor is opposite to a constructor. It is a method called when an object is no more required. The name of the destructor is the same as the class name and is preceded by a tilde (`). The destructor takes no arguments. C# manages the memory dynamically and uses a garbage collector, running on a separate thread, to execute all destructors on exit. The process of calling a destructor when an object is reclaimed by the garbage collector is called finalization. 14 7

8 // Destructors class A public int a; public A() a = 35; ~A () Console.WriteLine ("The allocated Memory is Destroyed"); public void display() Console.WriteLine ("The Value A is:" + a); class Main_A A a1 = new A (); a1.display (); 15 MEMBER INITIALIZATION 1. In addition to using constructors and methods to provide initial values to the objects, C# also allows us to assign initial values to individual data members at the time of declaration. 2. Example: class Initialization int number = 100; static double x = 1.0; String name = Sakthi ; Vehicle car = new Vehicle(800, maruti ); 3. When the variables are provided with the initial values at the time of declaration, the values are assigned as follows: a. Static variables are assigned when the class is loaded. b. Instance variables are assigned when an instance is created. 16 8

9 4. If the variables are not provided with the initial values as above, then they are assigned default values as dictated by their types. This is done as follows: a. Static variables are initialized to their default values when the class is loaded. b. Instance variables are initialized to their default values when an instance is created. 17 THE THIS REFERENCE 1. C# supports the keyword this which is a reference to the object that called the method. 2. The this reference is available within all the member methods and always refers to the current instance. 3. It is normally used to distinguish between local and instance variables that have the same name. 18 9

10 //THE THIS REFERENCE class Integer int x; int y; public void setxy(int x,int y) this.x = x; this.y = y; public void display() Console.WriteLine ("The X Value is: " + x); Console.WriteLine ("The Y Value is: " + y); class MainInteger Integer i = new Integer (); i.setxy (34,23); i.display (); 19 // NESTING OF CLASSES // CASE ONE public class Outer public int x; public class Inner public int y; class Main_class Outer o = new Outer (); Outer.Inner i = new Outer.Inner (); o.x = 67; i.y = 34; Console.WriteLine ("The X Value is: " + o.x ); Console.WriteLine ("The Y Value is: " + i.y ); 20 10

11 //CASE TWO public class Outer public int x; public class Inner public int y; public Outer o = new Outer (); class Main_Class Inner i = new Inner (); i.y = 90; i.o.x = 65; Console.WriteLine ("The X Value is: " + i.o.x ); Console.WriteLine ("The Y Value is: " + i.y); 21 CONSTANT MEMBERS 1. C# permits declaration of data fields of a class as constants. This can be done using the modifier const. Example: public const int size = 100; 2. It also means its value must be set when it is defined. Example: public const int size; is wrong and will cause a compilation error. 3. The const members are implicitly static, so we cannot declare them so explicitly using static 4. For example, the statement public static const int size = 100; is wrong and will produce compile time error

12 READ ONLY MEMBERS 1. There are situations where we would like to decide the value of a constant member at run time. We may also like to have different constant values for different object of the class. To overcome these shortcomings, C# provvides another modifier known as readonly to be used with data members. 2. This modifier is designed to set the value of the member using a constructor method, but cannot be modified later. 3. The readonly member may be declared as either static fields or instance fields. 23 // READ-ONLY MEMBERS class Numbers public readonly int m; public static readonly int n; public Numbers (int x) m = x; static Numbers () n = 100; public void display() Console.WriteLine ("The M Value is: " + m); Console.WriteLine ("The N Value is: " + n); class Main_Class Numbers n1 = new Numbers (150); n1.display (); 24 12

13 Why are you using Properties? class AClass private int afield; public void display() afield = 34; System.Console.WriteLine(aField); class Inner AClass a = new AClass(); The above program is known as to provide special methods known as accessor methods to have access to data members. Using accessor methods workds well and is a technique used by several OOP languages, including C++ and Java. However, it suffers from the following drawbacks: 1. We have to code the accessor methods manually. 2. User have to remember that they have to use accessor methods to work with data members. a.display(); 25 // IMPLEMENTING A PROPERTY class Number private int number; public int Anumber get return number; set number = value; class PropertyTest Number n = new Number (); n.anumber = 100; int m = n.anumber ; Console.WriteLine ("Number = " + m); 26 13

14 What are the powerful features of Properties? 1. A property can omit either a get clause or the set clause 2. A property that has only a getter is called a real only property, and a property that has only a setter is called a write only property. 3. Other than fetching the value of a variable, a get clause uses code to calcualte the value of the property using other fields and returns the results. 4. Like methods, properties are inheritable, we can use the modifiers abstract, virtual, new and override. 5. The static modifier can be used to declare properties that belong to the whole class rather that to a specific instance of the class. 27 INDEXERS Indexers are location indicators and are used to access class objects, just like accessing elements in an array. They are useful in cases where a class is a container for other objects. An Indexer looks like a property and is written the same way a property is written, but with two differences: 1. The indexer takes an index argument and looks like an array. 2. The indexer is declared using the name this. Ex: public double this [ int idx ] get //Return desired data set //Set desired data 28 14

15 DIFFERENCES BETWEEN INDEXERS AND PROPERTY 1. A property can be static member, whereas an indexer is always an instance member. 2. A get accessor of a property corresponds to a method no parameters, whereas a get accessor of an indexer corresponds to a method with the same formal parameter list as the indexer. 3. A set accessor of a property corresponds to a method with a single parameter named value, whereas a set accessor of an indexer corresponds to a method with the same formal parameter list as the indexer, plus the parameter named value. 4. It is an error for an indexer to declare a local variable with same name as an indexer parameter. 29 // IMPLEMENTING OF AN INDEXER using System.Collections ; class List ArrayList array = new ArrayList (); public object this [int index] get if (index < 0 && index >=array.count) return null; else return (array [index]); set array[index] = value; class Main_Class List list = new List (); list [0] = "123"; list [1] = "abc"; list [2] = "xyz"; for (int i = 0; i< list.count; i++) Console.WriteLine (list[i]); 30 15

16 INHERITANCE 31 INHERITANCE What is Inheritance? Inheritance is the mechanism which allows a class B to inherit properties/characteristicsattributes and methods of a class A. We say B inherits from A". A Super Class or Base Class or Parent Class B Sub Class or Derived Class or Child Class What are the Advantages of Inheritance 1. Reusability of the code. 2. To Increase the reliability of the code. 3. To add some enhancements to the base class

17 Inheritance achieved in two different forms 1. Classical form of Inheritance 2. Containment form of Inheritance Classical form of Inheritance A Super Class or Base Class or Parent Class B Sub Class or Derived Class or Child Class We can now create objects of classes A and B independently. Example: A a; //a is object of A B b; //b is object of B 33 In Such cases, we say that the object b is a type of a. Such relationship between a and b is referred to as is a relationship Example 1. Dog is a type of animal 2. Manager is a type of employee 3. Ford is a type of car Animal Horse Dog Lion 34 17

18 Containment Inheritance We can also define another form of inheritance relationship known as containership between class A and B. Example: class A class B B b; A a; // a is contained in b 35 In such cases, we say that the object a is contained in the object b. This relationship between a and b is referred to as has a relationship. The outer class B which contains the inner class A is termed the parent class and the contained class A is termed a child class. Example: 1. car has a radio. 2. House has a store room. 3. City has a road. Car object Radio object 36 18

19 Types of Inheritance 1. Single Inheritance (Only one Super Class and One Only Sub Class) 2. Multilevel Inheritance (Derived from a Derived Class) 3. Hierarchical Inheritance (One Super Class, Many Subclasses) 1. Single Inheritance (Only one Super Class and Only one Sub Class) A B Multilevel Inheritance (Derived from a Derived Class) A B 4. Hierarchical Inheritance (One Super class, Many Subclasses) C A B C D 38 19

20 DEFINING A SUBCLASS Syntax: class subclass-name : superclass-name Variable declaration; Methods declaration; Example: class B : A int x; void subclass(); 39 Example program for the Simple Inheritance class Item public void Company () Console.WriteLine ("Item Code = XXX"); class Fan:Item public void Model() Console.WriteLine ("Fan Model : Classic"); class SimpleInheritance Fan fan = new Fan (); fan.company (); fan.model (); 40 20

21 Note: Inheritance is transitive. (i) class A : B class B : C class C : A (ii) class A Class B : A 41 Some important characteristics of Inheritance are: 1. A derived class extends its direct base class. It can add new members to those it inherits. However, it cannot change or remove the definition on an inherited member. 2. Constructor and destructors are not inherited. All other members, regardless of their declared accessibility in base class, are inherited. 3. All instance of a class contains a copy of all instance fields declared in the class and its base classes. 4. A derived class can hide an inherited member. 5. A derived class can override an inherited member

22 CLASS VISIBILTY AND CLASS MEMBER VISIBILTY CONTROL Keyword Containing Classes Derived Classes Containing Program Anywhere outside the containing program private YES NO NO NO Protected YES YES NO NO Internal YES NO YES NO protected internal YES YES YES NO public YES YES YES YES ACCESIIBILITY DOMAIN OF CLASS MEMBERS Member modifier Public Internal Private public Every where Only Program Only class internal Only program Only program Only class private Only class Only class Only class 43 Accessibility of Baseclass Members class A A a = new A ( ); a.y = 5; a.z = 34; private int x; protected int y; public int z; class B : A public void SetXYZ () X = 10; Y = 20; Z = 30; // Object of A // Error; x is not accessible //ok //ok 44 22

23 Accessibility Constraints 1. The direct base class of a derived class must be at least as accessible as the derived class itself. 2. Accessibility domain of a member is never larger than that of the class containing it. 3. The return type of method must be atleast as accessible as the method itself Case 1 class A public class B : A Case 2 Class A Private class B Public int x; Case 3 Class A Public class B A method1() Internal A Method2 ( ) Public A Method3 45 ( ) // APPLICATION OF SINGLE INHERITANCE class Room1 public int length; public int breadth; public Room1(int x,int y) length = x; breadth = y; public int Area () return (length * breadth); class Room2 : Room1 int height; public Room2 (int x,int y,int z) : base (x,y) height = z; public int Volume() return (length * breadth * height); class InherTest Room2 room2 = new Room2 (14,12,10); int area1 = room2.area (); int volume1 = room2.volume (); Console.WriteLine ("Area = " + area1); Console.WriteLine ("Volume = " + volume1); 46 23

24 MULTILEVEL INHERITENCE // APPLICATION OF MULTILEVEL INHERITANCE class A protected int a; public A (int x) a = x; public void display_one() Console.WriteLine ("The A Value is: " + a); class B:A protected int b; public B (int x,int y):base(x) b = y; public void display_two() Console.WriteLine ("The A Value is: " + a); Console.WriteLine ("The B Value is: " + b); 47 class C:B int c; public C (int x,int y,int z):base(x,y) c = z; public void display_three() Console.WriteLine ("The A Value is: " + a); Console.WriteLine ("The B Value is: " + b); Console.WriteLine ("The C Value is: " + c); class MultiLevel C c = new C (10,20,30); c.display_one (); c.display_two (); c.display_three (); 48 24

25 // APPLICATION OF HIERARCHICAL INHERITANCE class Super protected int x; public Super(int x) this.x = x; class Sub_One:Super protected int y,y1; public Sub_One(int x,int y):base (x) this.y = y; public void display_sub_one() y1 = x - y; Console.WriteLine ("The Subtraction of the Two Numbers:" + y1); 49 class Sub_Two:Super protected int z,z1; public Sub_Two(int x,int z):base(x) this.z = z; public void display_sub_two() z1 = x + z; Console.WriteLine ("The Addition of the Two Numbers:" + z1); class MainSuper Sub_One so = new Sub_One (15,12); Sub_Two st = new Sub_Two (45,23); so.display_sub_one (); st.display_sub_two (); 50 25

26 OVERRIDING METHODS We have seen that a method defined in a super class is inherited by its subclass and is used by the objects created by the subclass. Method inheritance enables us to define and use methods repeatedly in sub classes. However, there may be occasions when we want an object to respond to the same method but behave differently when that method is called. That means, we should override the method defined in the super class. This is possible by defining a method in the subclass that has the same name, same arguments and same return type as a method in the super class. Then, when that method is called, the method defined in the subclass is invoked and executed instead of the one in the super class, provided that 1. We specify the method in base class as virtual 2. Implement the method in subclass using the keyword override This is known as overriding Note: 1. An override declaration may include the abstract modifier. 2. It is an error for an override declaration to include new or static or virtual modifier. 3. The overridden base method cannot be static or nonvirtual. 4. The overridden base method cannot be a sealed method. 51 // APPLICATION OF METHOD OVERRIDING class Super protected int x; public Super (int x) this.x = x; public virtual void Display() Console.WriteLine ("Super x = " + x); class Sub:Super int y; public Sub(int x,int y):base(x) this.y = y; public override void Display() Console.WriteLine ("Super x = " + x); Console.WriteLine ("Sub y = " + y); class OverrideTest Sub s1 = new Sub (100,200); s1.display (); 52 26

27 HIDING METHODS Now, let us assume that we wish to derive from a class provided by someone else and we also want to redefine some methods contained in it. Here, we cannot declare the base class methods as virtual. Then, how do we override a method without declaring it virtual? This is possible in C#. We can use the modifier new to tell the compiler that the derived class method hides the base class method. class Base public void Display() Console.WriteLine ("Base Method"); class Derived:Base public new void Display () Console.WriteLine ("Derived Method"); class HideTest Derived d = new Derived (); d.display (); 53 ABSTRACT CLASSES In a number of hierarchical applications, we would have one base class and a number of different derived classes. The top most base class simply acts as a base for others and is not useful on its own. In such situations, we might not want any one to create its objects. E can do this by making the base class abstract Some Characteristics of an abstract class are: 1. It cannot be instantiated directly. 2. It can have abstract members. 3. We cannot apply a sealed modifier to it

28 // ABSTRACT CLASSES abstract /*sealed*/ class Base protected int x = 23; //Console.WriteLine ("The X Value is: " + x); public void Display(); class Derived:Base public void Display () Console.WriteLine ("The X Value is: " + x); class HideTest //Base b = new Base (); Derived d = new Derived (); d.display (); 55 ABSTRACT METHODS Similar to abstract classes, we can also create abstract methods. When an instance method declaration includes the modifier abstract, the method is said to be an abstract method. An abstract method is implicitly a virtual method and does not provide any implementation. Some Characteristics of an abstract method are: 1. It cannot have implementation. 2. Its implementation must be provided in non abstract derived classes by overriding the method. 3. It can be declared only in abstract classes. 4. It cannot take either static or virtual modifiers 5. An abstract declaration is permitted to override a virtual method

29 // ABSTRACT CLASSES AND ABSTRACT METHODS abstract class Base public abstract void Draw (); class Derived:Base public override void Draw () Console.WriteLine ("This is Draw"); class HideTest Derived d = new Derived (); d.draw (); 57 // SEALED CLASSES: PREVENTING INHERITANCE sealed class A protected int x; sealed class B:A public void display() x = 34; Console.WriteLine ("The X Value is :" + x); class MainSealed B b = new B (); b.display (); 58 29

30 // SEALED METHOD class A public virtual void display() Console.WriteLine ("Welcome_One"); class B:A public sealed override void display() Console.WriteLine ("Welcome_Two"); class C:B public override void display() Console.WriteLine ("Welcome_Three"); class MainSealed C c = new C (); c.display (); 59 POLYMORPHISM 60 30

31 POLYMORPHISM Polymorphism mean one name, many forms, essentially, polymorphism is the capability of one object to behave in multiple ways. Polymorphism Operation Polymorphism Using overloaded methods Inclusion Polymorphism Using virtual method OPERATION POLYMORPHISM The overloaded methods are selected for invoking by matching arguments, in terms of number, type and order. This information is known to the compiler at the time of compilation and, therefore, the compiler is able to select and bind the appropriate method to the object for a particular call at compile time itself. This process is called early binding, or static binding, or static linking. It is also known as compiling time polymorphism. time. Early binding simply means that an object is bound to its method call at compile 61 // OPERATION POLYMORPHISM class Dog class Cat class Operation static void Call (Dog d) Console.WriteLine ("Dog is Called"); static void Call (Cat c) Console.WriteLine ("Cat is Called"); Dog dog = new Dog (); Cat cat = new Cat (); Call(dog); Call(cat); 62 31

32 CASTING BETWEEN TYPES One of the important aspects in the application of inheritance, namely, type casting between classes. There are a number of situations where we need to apply casting between the objects of base and derived classes. C# permits upcasting of an object of a derived class to an object of its base class. However, we cannot downcast implicitly an object of a base class to an object of the derived classes. class Base Class Derived:Base Base b = new Derived ( ); // Upcasting Derived d = new Base ( ); //Downcasting, Error. 63 INCLUSION POLYMORPHISM Inclusion polymorphism is achieved through the use of virtual functions. Assume that the class A implements a virtual method M and classes B and C that are derived from A override the virtual method M. When B is cast to A, a call to the method M from A is dispatched to B. Similarly, when C is cast to A, a call to M is dispatched to C. The decision on exactly which method to call is delayed until runtime and, therefore, it is also known as runtime polymorphism. Since the method is linked with a particular class much later after compilation, this process is termed late binding. It is also known as dynamic binding, because the selection of the appropriate method is done dynamically at runtime. M A B C 64 32

33 // INCLUSION POLYMORPHISM class Maruthi public virtual void Display () Console.WriteLine ("Maruthi Car"); class Esteem:Maruthi public override void Display() Console.WriteLine ("Maruthi Esteem"); class Zen:Maruthi public override void Display() Console.WriteLine ("Maruthi Zen"); 65 class Inclusion Maruthi m = new Maruthi (); m = new Esteem (); //Upcasting m.display (); m = new Zen (); //UpCasting m.display (); 66 33

34 INTERFACE 67 DEFINING AN INTERFACE INTERFACES: MULTIPLE INHERITANCE An interface can contain one or more methods, properties, indexers and events but none of them are implemented in the interface itself. It is the responsibility of the class that implements the interface to define the code for implementation of these members. Syntax: Ex: interface Interfacename Member declarations; interface Show void Display ( ); 68 34

35 Ex: interface Example int Aproperty get; event someevent Changed; void Display( ); The accessibility of an interface can be controlled by using the modifiers public, protected, internal and private. We may also apply the modifier new on nested interfaces. It specifies that the interface hides an inherited member by the same name. DIFFERENCE BETWEEN CLASSES AND INTERFACES 1. All the members of an interface are implicitly public and abstract. 2. An interface cannot contain fields, constructors and destructors. 3. Its members cannot be declared static. 4. Since the methods in an interface are abstract, they do not include implementation code. 5. An Interface can inherit multiple interfaces. 69 EXTENDING INTERFACES Syntax: interface name2 : name1 Members of name2 Ex: interface Addition int Add (int x,int y); interface Compute : Addition int Sub(int x, int y); Ex: interface I interface I interface I3 : I1, I

36 IMPLEMENTING INTERFACES Syntax: class classname : interfacename Body of classname class classname : superclass, interface1, interface2 Body of classname Ex: class A : I class B : A, I1, I IMPLEMENTATION OF MULTIPLE INTERFACES interface Addition int Add(); interface Multiplication int Mul(); class Computation:Addition,Multiplication int x,y; public Computation(int x,int y) this.x = x; this.y = y; public int Add() return(x+y); public int Mul() return (x*y); 72 36

37 class InterfaceTest Computation com = new Computation (10,20); Addition add = (Addition) com; Console.WriteLine ("Sum = " + add.add ()); Multiplication mul = (Multiplication) com; Console.WriteLine ("Product = " + mul.mul ()); 73 MULTIPLE IMPLEMENTATION OF AN INTERFACE interface Area double Compute(double x); class Square : Area public double Compute(double x) return(x*x); class Circle : Area public double Compute(double x) return (Math.PI * x * x); 74 37

38 class InterfaceTest Square sqr = new Square (); Circle cir = new Circle (); Area area; area = sqr as Area ; Console.WriteLine ("Area of Square = " + area.compute (10.0)); area = cir as Area ; Console.WriteLine ("Area of Circle = " + area.compute (10.0)); 75 INHERITING A CLASS THAT IMPLEMENTS AN INTERFACE interface Display void Print (); class B : Display public void Print () Console.WriteLine ("Base Display"); class D : B public new void Print () Console.WriteLine ("Derived Display"); 76 38

39 class InterfaceTest D d = new D (); d.print (); Display dis = (Display) d; dis.print (); 77 EXPLICIT INTERFACE IMPLEMENTATION interface I1 void Display(); interface I2 void Display(); class C1 : I1,I2 void I1.Display () Console.WriteLine ("I1 Display"); void I2.Display () Console.WriteLine ("I2 Display"); 78 39

40 class InterfaceTest C1 c = new C1 (); I1 i1 = (I1) c; i1.display (); I2 i2 = (I2) c; i2.display (); 79 ABSTRACT CLASS AND INTERFACES interface A void Display(); abstract class B : A public abstract void Display (); class C : B public override void Display () Console.WriteLine ("Welcome"); class InterfaceTest C c = new C (); c.display (); 80 40

41 OPERATOR OVERLOADING 81 DEFINITION: Vector u1, u2, u3; // initialize u1 and u2 here u3 = u1 + u2; // adding two objects, u1 and u2 Where Vector is a class or a struct. Two vectors u1 and u2 are added give a third vector (u3). This means, C# has the ability to provide the operators with a special meaning for a data type. This mechanism of giving such special meaning to an operator is known as operator overloading. Overloadable Operators Operator that cannot be overloaded Category Binary arithmetic Unary arithmetic Binary bitwise Unary bitwise Operators +, *, /, -, % +, -, ++, -- &,, ^, <<, >>!, ~, true, false Category Conditional operators Compound assignment Others Operators Operators &&, +=, -=, *=, /=, %= [ ], ( ), =,?, :, ->, typeof, sizeof, is, as Logical operators ==,!=, >, >=, <, <= 82 41

42 NEED FOR OPERATOR OVERLOADING 1. Mathematical or physical modeling where we use classes to represent objects such as coordinates, vectors, matrices, tensors, complex numbers and so on. 2. Graphical programs where co-ordinate-related objects are used to represent positions on the screen. 3. Financial programs where a class represents an amount of money. 4. Text manipulations where classes are used to represent strings and sentences. DEFINING OPERATOR OVERLOADING To define an additional task to an operator, we must specify what it means in relation to the class to which the operator is applied. This is done with help of a special method called operator method. The general form of an operator method is: public static retval operator op(arglist_1,arglist_2) Method body 83 The key features of operator methods are: 1. They must be defined as public and static 2. The retval (return value) type is the type that we get when we use this operator. But, technically, it can be of any type. 3. The arglist is the list of arguments passed. The number of arguments will be one for the unary operators and two for the binary operators. 4. In the case of unary operators, the argument must be the same type as that of the enclosing class or struct. 5. In the case of binary operators, the first argument must be of the same type as that of the enclosing class or struct and the second may be of any type

43 Overloading unary minus class Space int x,y,z; public Space(int a,int b,int c) x = a; y = b; z = c; public void Display() Console.WriteLine (" " + x); Console.WriteLine (" " + y); Console.WriteLine (" " + z); Console.WriteLine (); public static void operator- (Space s) s.x = - s.x ; s.y = - s.y ; s.z = - s.z ; 85 class SpaceTest Space s = new Space (10,-20,30); Console.Write("S :"); s.display (); -s; Console.Write ("S :"); s.display (); 86 43

44 Overloading + Operator class Complex double x; double y; public Complex(double real,double imag) x = real; y = imag; public static Complex operator + (Complex c1,complex c2) Complex c3; c3.x = c1.x + c2.x; c3.y = c1.y + c2.y; return (c3); public void Display() Console.Write (x); Console.Write (" + j " + y); Console.WriteLine (); 87 class ComplexTest Complex a,b,c; a = Complex(2.5,3.5); b = Complex(1.6,2.7); c = a + b; // is nothing but c = + (a,b), but not implemented Console.Write(" a = "); a.display (); Console.Write(" b = "); b.display (); Console.Write(" c = "); c.display (); 88 44

45 complex operator + (complex c1, complex c2) complex temp; temp 4.10 x 6.20 y return temp.x = c1.x + c2.x ; temp.y = c1.y + c2.y ; return (temp); C3 = + ( C1, C2 ) 4.10 x 6.20 y 2.50 x 3.50 y 1.60 x y class Relational public int a; > Operator Overloaded public Relational(int x) a = x; public static Relational operator>(relational R1,Relational R2) Relational relation; relation = R1.a > R2.a; return (relation); class Main_Relational Relational R1, R2, R3; Relational R1 = new Relational(20); Relational R2 = new Relational(10); R3 = R1 > R2; Console.WriteLine("The Biggest Value is:" + R3); 90 45

46 class Relational public int a; + Operator Overloaded public Relational(int x) a = x; public static int operator +(Relational R1,Relational R2) return (R1.a + R2.a); class Main_Relational Relational R1, R2; R1 = new Relational(20); R2 = new Relational(10); Console.WriteLine("The Biggest Value is:" + (R1 + R2)); 91 public class fibonacci public int f0, f1, fib; class Main_fibonacci fibonacci fi = new fibonacci (); public fibonacci() f0 = 0; f1 = 1; fib = f0 + f1; public static fibonacci operator ++(int x) f0 = f1; f1 = fib; fib = f0 + f1; for(int i=0;i<10;++i) fi.display (); ++fi; return (fibonacci); public void display() Console.WriteLine(fib); ++ Operator Overloaded 92 46

47 MANAGING ERRORS AND EXCEPTIONS 93 ERROR Errors are mistakes that can make a program go wrong. An error may produce an incorrect output or may terminate the execution of the program abruptly or even may cause the system to crash. TYPES OF ERROR 1. Compile Time Error 2. Run Time Error 1. Compile Time Errors Missing Semicolon. Missing brackets in classes and methods Misspelling of identifiers and keywords Use of = in place of == operator, etc. 2. Run Time Errors Dividing an integer by zero Accessing an element that is out of the bounds of an array Converting an invalid string to a number or vice versa. Attempting to use a negative size for an array

48 class Exception int a = 10; int b = 5; int c = 5; int x = a / (b - c); Console.WriteLine ("X = " + x); int y = a / (b + c); Console.WriteLine ("Y = " + x); 95 EXCEPTION An Exception is a condition that is caused by a run-time error in the program. If the exception object is not caught and handled properly, the compiler will display an error message and will terminate the program If we want the program to continue with the execution of the remaining code, then we should try to catch the exception object thrown by the error condition and then display an appropriate message for taking corrective actions. This task is known as exception handling. EXCEPTION HANDLING MECHANISM 1. Find the problem (Hit the exception) 2. Inform that an error has occurred (Throw the exception) 3. Receive the error information (Catch the exception) 4. Take corrective actions ( Handle the exception) 96 48

49 Throws Exception object try Block Statement that caused an exception catch Block Statements that handle the exception Exception object creator Exception handler Throw Point Exceptions are thrown by methods that are invoked from within the try blocks. The point at which an exception is thrown is called the throw point. Once an exception is thrown to the catch block, control cannot return to the throw point. 97 SYNTAX OF EXCEPTION HANDLING CODE try Statement; catch(exception e) Statement; //generates an exception //process the exception 98 49

50 USING TRY AND CATCH FOR EXCEPTION HANDLING class Ex int a = 10; int b = 5; int c = 5; try int x = a / (b - c); Console.WriteLine ("X = " + x); catch (Exception e) Console.WriteLine ("Division by Zero"); int y = a / (b + c); Console.WriteLine ("Y = " + y); 99 COMMON C# EXCEPTIONS Exception Class SystemException ArgumentException DivideByZeroException FormatException IndexOutofRangeException StackOverflowException ArrayTypeMismatchException ArithmeticException Cause of Exception A failed run time check; used as a base class for other exceptions An argument to a method was invalid An attempt was made to divide by zero The format of an argument is wrong An array index is out of bounds A stack has overflowed Attempt to store the wrong type of object in an array Arithmetic over or underflow has occurred

51 MULTIPLE CATCH STATEMENTS Syntax: try Statement; // generates an exception catch(exception Type 1 e) Statement; // processes exception type 1 catch(exception Type 2 e) Statement; // processes exception type 2... catch(exception Type N e) Statement; // processes exception type N Note: C# does not require any processing of the exception at all. We can simply have a catch statement with an empty block to avoid program abortion. Ex: catch (Exception e) 101 USING MULTIPLE CATCH BLOCKS class Multiple int [] a = 5,10; int b = 5; try int x = a[2] / b - a[1]; catch(arithmeticexception e) Console.WriteLine ("Division By Zero"); catch(indexoutofrangeexception e) Console.WriteLine ("Array index error"); catch(arraytypemismatchexception e) Console.WriteLine ("Wrong data type"); int y = a[1] / a[0]; Console.WriteLine ("Y =" + y);

52 THE EXCEPTION HIERARCHY CASE ONE try //Throw divide by Zero Exception catch(exception e) catch(dividebyzeroexception e) CASE TWO try //Throw divide by Zero Exception catch(dividebyzeroexception e) catch(exception e)

53 GENERAL CATCH HANDLER A catch block which will catch any exception is called a general catch handler. A general catch handler does not specify any parameter and can be written as: try // causes an exception catch // no parameters // handles error 105 USING FINALLY STATEMENT C# supports another statement known as a finally statement that can be used to handle an exception that is not caught by any of the previous catch statements. A finally block can be used to handle any exception generated within a try block. It may be added immediately after the try block or after the last catch try try finally catch ( ) catch (------) finally

54 Try Block Error 1 No Error Error 2 Catch Block 1 Catch Block 2 Finally Block Leaving Try Block 107 NESTED TRY BLOCKS try (Point 1) catch finally try catch finally (Point 2) (Point 3) (Point 4)

55 When nested try blocks are executed, the exceptions that are thrown at various points are handled as follows: 1. The Points P1 and P4 are outside the inner try block and therefore any exceptions thrown at these points will be handled by the catch in the outer block. The inner block is simply ignored. 2. Any exception thrown at point P2 will be handled by the inner catch handler and the inner finally will be executed. The execution will continue at point P4 in the program. 3. If there is not suitable catch handler to catch an exception thrown at P2, the control will leave the inner block (after executing the inner finally) and look after a suitable catch handler in the outer block. If a suitable one is found, then that handler is executed followed by the outer finally code. Remember, the code at Point 4 will be skipped. 4. If an exception is thrown at point P3, it is treated as if it had been thrown by the outer try block and, therefore, the control will immediately leave the inner block (after executing the inner finally) and search for a suitable catch handler in the outer block. 109 IMPLEMENTING NESTED TRY BLOCKS class NestedTry static int m = 10; static int n = 0; static void Division() try int k = m / n; catch (ArgumentException e) Console.WriteLine ("Caught an Exception"); finally Console.WriteLine ("Inside Division Method");

56 try Division (); catch(dividebyzeroexception e) Console.WriteLine ("Caught an Exception"); finally Console.WriteLine ("Inside Main Method"); 111 THROWING OUR OWN EXCEPTIONS There may be times when we would like to throw our own exceptions. We can do this by using the keyword throw as follows: throw new Throwoble_subclass Ex: throw new ArithmeticException ( ); throw new FormatException ( );

57 class MyException:Exception public MyException(string message) class TestMyException int x = 5, y = 1000; try float z = (float) x / (float) y; if(z<0.01) throw new MyException ("Number is too small"); 113 catch(myexception e) Console.WriteLine ("Caught my exception"); Console.WriteLine (e.message ); finally Console.WriteLine ("I am always here");

58 CHECKED AND UNCHECKED OPERATORS class Check int a = ; int b = ; try int m = checked(a * b); catch(overflowexception e) Console.WriteLine (e.message ); 115 DELEGATES AND EVENTS

59 Introduction C# implements the callback technique in a much safer and more object oriented manner, using a kind of object called delegate object. A delegate object is a special type of object that contains the details of a method rather than data. Delegates in C# are used for two purposes: 1. Callback 2. Event Handling DELEGATES Delegate is a person acting for another person. In C#, it really means a method acting for another method. A delegate in C# is a class type object and is used to invoke a method that has been encapsulated into it at the time of its creation. Creating and using delegates involve four steps. They include: Delegate declaration Delegate methods definition Delegate instantiation Delegate invocation class. 117 A delegate declaration defined a class using the class System.Delegate as a base DELEGATE DECLARATION modifier delegate return-type delegate-name (parameter) modifier new, public, protected, private, internal Ex: delegate void SimpleDelegate( ); delegate int MathOperation(int x,int y); public delegate int CompareItems(Object o1,object o2); Delegate may be defined in the following places: Inside a class. Outside all class. As the top level object in a namespace. Delegate types are implicitly sealed and therefore it is not possible to derive any type from a delegate type

60 DELEGATE METHOD The methods whose references are encapsulated into a delegate instance are known as delegate methods or callable entities. The signature and return type of delegate methods must exactly match the signature and return type of the delegate. delegate void Delegate1( ); public void F1( ) Console.WriteLine ( F1 ); static public void F2 ( ) Console.WriteLine ( F2 ); DELEGATE INSTANTATION A delegate creation-expression is used to create a new instance of a delegate. new delegate-type (expression); DELEGATE INVOCATION delegate_object (parameters_list); 119 //delegate declaration delegate int ArithOp(int x,int y); class MathOperation //delegate methods definition public static int Add(int a,int b) return (a + b); public static int Sub(int a,int b) return (a - b); class DelegateTest ArithOp operation1 = new ArithOp (MathOperation.Add ); ArithOp operation2 = new ArithOp (MathOperation.Sub ); int result1 = operation1(200,100); int result2 = operation2(200,100); Console.WriteLine ("Result1 = " + result1); Console.WriteLine ("Result2 = " + result2);

61 MULTICAST DELEGATES Single Delegate can invoke only one method. However, it is possible for certain delegates to hold and invoke multiple methods. Such delegates are called multicast delegates, also known as combinable delegates. 1. The return type of the delegates must be void 2. None of the parameters of the delegate type can be declared as output parameter, using out keyword. 121 delegate void MDelegate(); class DM static public void Display() Console.WriteLine ("NEW DELHI"); static public void Print() Console.WriteLine ("NEW YORK"); class MTest MDelegate m1 = new MDelegate (DM.Display ); MDelegate m2 = new MDelegate (DM.Print ); MDelegate m3 = m1 + m2; MDelegate m4 = m2 + m1; MDelegate m5 = m3 - m2; m3(); m4(); m5();

62 EVENTS An event is a delegate type class member that is used by the object or class to provide a notification to other objects that a event has occurred. The client object can act on an event by adding an event handler to the event. Events are declared using the simple event declaration format as follows: modifier event type event-name; The modifier may be new, a valid combination of the four access modifiers, and a valid combination of static, virtual, override and sealed. The type of an event declaration must be a delegate type and the delegate must be as accessible as the event itself. Ex: public event EventHandler Click; public event RateChange Rate; EventHandler and RateChange are delegates and Click and Rate are events. 123 //delegate declaration first public delegate void EDelegate(string str); class EventClass //declaration of event public event EDelegate Status; public void TriggerEvent() if(status!= null) Status("Event Triggered"); class EventTest EventClass ec = new EventClass (); EventTest et = new EventTest (); ec.status += new EDelegate (et.eventcatch); ec.triggerevent (); public void EventCatch(string str) Console.WriteLine (str);

63 THE END

Object-Oriented Programming

Object-Oriented Programming Object-Oriented Programming 1. What is object-oriented programming (OOP)? OOP is a technique to develop logical modules, such as classes that contain properties, methods, fields, and events. An object

More information

CHETTINAD COLLEGE OF ENGINEERING AND TECHNOLOGY DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING II INTERNAL PORTION NOTES

CHETTINAD COLLEGE OF ENGINEERING AND TECHNOLOGY DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING II INTERNAL PORTION NOTES CHETTINAD COLLEGE OF ENGINEERING AND TECHNOLOGY DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING II INTERNAL PORTION NOTES POLYMORPHISM Polymorphism mean one name, many forms, essentially, polymorphism is

More information

PES INSTITUTE OF TECHNOLOGY (BSC) V MCA, Second IA Test, OCTOBER 2017 Programming Using C#.NET (13MCA53) Solution Set Faculty: Jeny Jijo

PES INSTITUTE OF TECHNOLOGY (BSC) V MCA, Second IA Test, OCTOBER 2017 Programming Using C#.NET (13MCA53) Solution Set Faculty: Jeny Jijo PES INSTITUTE OF TECHNOLOGY (BSC) V MCA, Second IA Test, OCTOBER 2017 Programming Using C#.NET (13MCA53) Solution Set Faculty: Jeny Jijo 1. What is Encapsulation? Explain the two ways of enforcing encapsulation

More information

DC69 C# and.net JUN 2015

DC69 C# and.net JUN 2015 Solutions Q.2 a. What are the benefits of.net strategy advanced by Microsoft? (6) Microsoft has advanced the.net strategy in order to provide a number of benefits to developers and users. Some of the major

More information

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe OBJECT ORIENTED PROGRAMMING USING C++ CSCI 5448- Object Oriented Analysis and Design By Manali Torpe Fundamentals of OOP Class Object Encapsulation Abstraction Inheritance Polymorphism Reusability C++

More information

Hierarchical inheritance: Contains one base class and multiple derived classes of the same base class.

Hierarchical inheritance: Contains one base class and multiple derived classes of the same base class. 1. What is C#? C# (pronounced "C sharp") is a simple, modern, object oriented, and type safe programming language. It will immediately be familiar to C and C++ programmers. C# combines the high productivity

More information

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity. OOPS Viva Questions 1. What is OOPS? OOPS is abbreviated as Object Oriented Programming system in which programs are considered as a collection of objects. Each object is nothing but an instance of a class.

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming Overview of OOP Object Oriented Programming is a programming method that combines: a) Data b) Instructions for processing that data into a self-sufficient object that can be used within a program or in

More information

UNIT - V. Inheritance Interfaces and inner classes Exception handling Threads Streams and I/O

UNIT - V. Inheritance Interfaces and inner classes Exception handling Threads Streams and I/O UNIT - V Inheritance Interfaces and inner classes Exception handling Threads Streams and I/O 1 INHERITANCE 2 INHERITANCE What is Inheritance? Inheritance is the mechanism which allows a class B to inherit

More information

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT Two Mark Questions UNIT - I 1. DEFINE ENCAPSULATION. Encapsulation is the process of combining data and functions

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

STRUCTURING OF PROGRAM

STRUCTURING OF PROGRAM Unit III MULTIPLE CHOICE QUESTIONS 1. Which of the following is the functionality of Data Abstraction? (a) Reduce Complexity (c) Parallelism Unit III 3.1 (b) Binds together code and data (d) None of the

More information

Object-Oriented Programming (OOP) Fundamental Principles of OOP

Object-Oriented Programming (OOP) Fundamental Principles of OOP Object-Oriented Programming (OOP) O b j e c t O r i e n t e d P r o g r a m m i n g 1 Object-oriented programming is the successor of procedural programming. The problem with procedural programming is

More information

Get Unique study materials from

Get Unique study materials from Downloaded from www.rejinpaul.com VALLIAMMAI ENGNIEERING COLLEGE SRM Nagar, Kattankulathur 603203. DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Year & Semester : IV Section : EEE - 1 & 2 Subject Code

More information

OBJECT ORIENTED PROGRAMMING. Ms. Ajeta Nandal C.R.Polytechnic,Rohtak

OBJECT ORIENTED PROGRAMMING. Ms. Ajeta Nandal C.R.Polytechnic,Rohtak OBJECT ORIENTED PROGRAMMING Ms. Ajeta Nandal C.R.Polytechnic,Rohtak OBJECT ORIENTED PARADIGM Object 2 Object 1 Data Data Function Function Object 3 Data Function 2 WHAT IS A MODEL? A model is an abstraction

More information

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University) Estd: 1994 JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli - 621014 (An approved by AICTE and Affiliated to Anna University) ISO 9001:2000 Certified Subject Code & Name : CS 1202

More information

Compaq Interview Questions And Answers

Compaq Interview Questions And Answers Part A: Q1. What are the difference between java and C++? Java adopts byte code whereas C++ does not C++ supports destructor whereas java does not support. Multiple inheritance possible in C++ but not

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8. OOPs Concepts 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8. Type Casting Let us discuss them in detail: 1. Data Hiding: Every

More information

A Short Summary of Javali

A Short Summary of Javali A Short Summary of Javali October 15, 2015 1 Introduction Javali is a simple language based on ideas found in languages like C++ or Java. Its purpose is to serve as the source language for a simple compiler

More information

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 20, 2014 Abstract

More information

OBJECT ORİENTATİON ENCAPSULATİON

OBJECT ORİENTATİON ENCAPSULATİON OBJECT ORİENTATİON Software development can be seen as a modeling activity. The first step in the software development is the modeling of the problem we are trying to solve and building the conceptual

More information

Chapter 5 Object-Oriented Programming

Chapter 5 Object-Oriented Programming Chapter 5 Object-Oriented Programming Develop code that implements tight encapsulation, loose coupling, and high cohesion Develop code that demonstrates the use of polymorphism Develop code that declares

More information

Chapter 1: Object-Oriented Programming Using C++

Chapter 1: Object-Oriented Programming Using C++ Chapter 1: Object-Oriented Programming Using C++ Objectives Looking ahead in this chapter, we ll consider: Abstract Data Types Encapsulation Inheritance Pointers Polymorphism Data Structures and Algorithms

More information

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information

CH. 2 OBJECT-ORIENTED PROGRAMMING

CH. 2 OBJECT-ORIENTED PROGRAMMING CH. 2 OBJECT-ORIENTED PROGRAMMING ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER (WILEY 2016) OBJECT-ORIENTED

More information

VALLIAMMAI ENGINEERING COLLEGE

VALLIAMMAI ENGINEERING COLLEGE VALLIAMMAI ENGINEERING COLLEGE SRM Nagar, Kattankulathur 603 203 DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING QUESTION BANK B.E. - Electrical and Electronics Engineering IV SEMESTER CS6456 - OBJECT ORIENTED

More information

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully

More information

Declarations and Access Control SCJP tips

Declarations and Access Control  SCJP tips Declarations and Access Control www.techfaq360.com SCJP tips Write code that declares, constructs, and initializes arrays of any base type using any of the permitted forms both for declaration and for

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017 Overview of OOP Dr. Zhang COSC 1436 Summer, 2017 7/18/2017 Review Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in square brackets: l = [1, 2, "a"] (access by index, is mutable

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Object Oriented Programming Designed and Presented by Dr. Ayman Elshenawy Elsefy Dept. of Systems & Computer Eng.. Al-Azhar University Website: eaymanelshenawy.wordpress.com Email : eaymanelshenawy@azhar.edu.eg

More information

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE PART A UNIT I 1. Differentiate object oriented programming from procedure oriented programming. 2. Define abstraction and encapsulation. 3. Differentiate

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 21, 2013 Abstract

More information

Data Structures using OOP C++ Lecture 3

Data Structures using OOP C++ Lecture 3 References: th 1. E Balagurusamy, Object Oriented Programming with C++, 4 edition, McGraw-Hill 2008. 2. Robert L. Kruse and Alexander J. Ryba, Data Structures and Program Design in C++, Prentice-Hall 2000.

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,

More information

What are the characteristics of Object Oriented programming language?

What are the characteristics of Object Oriented programming language? What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is

More information

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs. Local Variable Initialization Unlike instance vars, local vars must be initialized before they can be used. Eg. void mymethod() { int foo = 42; int bar; bar = bar + 1; //compile error bar = 99; bar = bar

More information

Data Structures (list, dictionary, tuples, sets, strings)

Data Structures (list, dictionary, tuples, sets, strings) Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in brackets: l = [1, 2, "a"] (access by index, is mutable sequence) Tuples are enclosed in parentheses: t = (1, 2, "a") (access

More information

Introduction to C# Applications

Introduction to C# Applications 1 2 3 Introduction to C# Applications OBJECTIVES To write simple C# applications To write statements that input and output data to the screen. To declare and use data of various types. To write decision-making

More information

C++ Important Questions with Answers

C++ Important Questions with Answers 1. Name the operators that cannot be overloaded. sizeof,.,.*,.->, ::,? 2. What is inheritance? Inheritance is property such that a parent (or super) class passes the characteristics of itself to children

More information

Prasanth Kumar K(Head-Dept of Computers)

Prasanth Kumar K(Head-Dept of Computers) B.Sc (Computer Science) Object Oriented Programming with Java and Data Structures Unit-II 1 1. Define operator. Explain the various operators in Java. (Mar 2010) (Oct 2011) Java supports a rich set of

More information

Instantiation of Template class

Instantiation of Template class Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or built-in types. Example: stack of int or stack of double

More information

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor. 3.Constructors and Destructors Develop cpp program to implement constructor and destructor. Constructors A constructor is a special member function whose task is to initialize the objects of its class.

More information

Polymorphism Part 1 1

Polymorphism Part 1 1 Polymorphism Part 1 1 What is Polymorphism? Polymorphism refers to a programming language s ability to process objects differently depending on their data type or class. Number person real complex kid

More information

Java: introduction to object-oriented features

Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer

More information

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages Preliminaries II 1 Agenda Objects and classes Encapsulation and information hiding Documentation Packages Inheritance Polymorphism Implementation of inheritance in Java Abstract classes Interfaces Generics

More information

Object Oriented Programming. Solved MCQs - Part 2

Object Oriented Programming. Solved MCQs - Part 2 Object Oriented Programming Solved MCQs - Part 2 Object Oriented Programming Solved MCQs - Part 2 It is possible to declare as a friend A member function A global function A class All of the above What

More information

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1 Polymorphism Part 1 What is Polymorphism? Polymorphism refers to a programming language s ability to process objects differently depending on their data type or class. Number person real complex kid adult

More information

Index COPYRIGHTED MATERIAL

Index COPYRIGHTED MATERIAL Index COPYRIGHTED MATERIAL Note to the Reader: Throughout this index boldfaced page numbers indicate primary discussions of a topic. Italicized page numbers indicate illustrations. A abstract classes

More information

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed CREATED BY: Muhammad Bilal Arslan Ahmad Shaad JAVA Chapter No 5 Instructor: Muhammad Naveed Muhammad Bilal Arslan Ahmad Shaad Chapter No 5 Object Oriented Programming Q: Explain subclass and inheritance?

More information

CS304 Object Oriented Programming

CS304 Object Oriented Programming 1 CS304 Object Oriented Programming 1. Which of the following is the way to extract common behaviour and attributes from the given classes and make a separate class of those common behaviours and attributes?

More information

Operators and Expressions

Operators and Expressions Operators and Expressions Conversions. Widening and Narrowing Primitive Conversions Widening and Narrowing Reference Conversions Conversions up the type hierarchy are called widening reference conversions

More information

CS260 Intro to Java & Android 03.Java Language Basics

CS260 Intro to Java & Android 03.Java Language Basics 03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance

More information

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner. HAS-A Relationship Association is a relationship where all objects have their own lifecycle and there is no owner. For example, teacher student Aggregation is a specialized form of association where all

More information

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

Cpt S 122 Data Structures. Course Review Midterm Exam # 2 Cpt S 122 Data Structures Course Review Midterm Exam # 2 Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Midterm Exam 2 When: Monday (11/05) 12:10 pm -1pm

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 12 Thomas Wies New York University Review Last lecture Modules Outline Classes Encapsulation and Inheritance Initialization and Finalization Dynamic

More information

Framework Fundamentals

Framework Fundamentals Questions Framework Fundamentals 1. Which of the following are value types? (Choose all that apply.) A. Decimal B. String C. System.Drawing.Point D. Integer 2. Which is the correct declaration for a nullable

More information

Introduction Of Classes ( OOPS )

Introduction Of Classes ( OOPS ) Introduction Of Classes ( OOPS ) Classes (I) A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions. An object is an instantiation of a class.

More information

CS304 Object Oriented Programming Final Term

CS304 Object Oriented Programming Final Term 1. Which of the following is the way to extract common behaviour and attributes from the given classes and make a separate class of those common behaviours and attributes? Generalization (pg 29) Sub-typing

More information

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING THROUGH C++ Practical: OOPS THROUGH C++ Subject Code: 1618407 PROGRAM NO.1 Programming exercise on executing a Basic C++

More information

Interview Questions of C++

Interview Questions of C++ Interview Questions of C++ Q-1 What is the full form of OOPS? Ans: Object Oriented Programming System. Q-2 What is a class? Ans: Class is a blue print which reflects the entities attributes and actions.

More information

I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++

I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++ No. of Printed Pages : 3 I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination 05723. June, 2015 BCS-031 : PROGRAMMING IN C ++ Time : 3 hours Maximum Marks : 100 (Weightage 75%)

More information

Department of Computer science and Engineering Sub. Name: Object oriented programming and data structures Sub. Code: EC6301 Sem/Class: III/II-ECE Staff name: M.Kavipriya Two Mark Questions UNIT-1 1. List

More information

CLASSES AND OBJECTS IN JAVA

CLASSES AND OBJECTS IN JAVA Lesson 8 CLASSES AND OBJECTS IN JAVA (1) Which of the following defines attributes and methods? (a) Class (b) Object (c) Function (d) Variable (2) Which of the following keyword is used to declare Class

More information

Exercise: Singleton 1

Exercise: Singleton 1 Exercise: Singleton 1 In some situations, you may create the only instance of the class. 1 class mysingleton { 2 3 // Will be ready as soon as the class is loaded. 4 private static mysingleton Instance

More information

Data type of a pointer must be same as the data type of the variable to which the pointer variable is pointing. Here are a few examples:

Data type of a pointer must be same as the data type of the variable to which the pointer variable is pointing. Here are a few examples: Unit IV Pointers and Polymorphism in C++ Concepts of Pointer: A pointer is a variable that holds a memory address of another variable where a value lives. A pointer is declared using the * operator before

More information

CPS 506 Comparative Programming Languages. Programming Language

CPS 506 Comparative Programming Languages. Programming Language CPS 506 Comparative Programming Languages Object-Oriented Oriented Programming Language Paradigm Introduction Topics Object-Oriented Programming Design Issues for Object-Oriented Oriented Languages Support

More information

CS-202 Introduction to Object Oriented Programming

CS-202 Introduction to Object Oriented Programming CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction

More information

What is Inheritance?

What is Inheritance? Inheritance 1 Agenda What is and Why Inheritance? How to derive a sub-class? Object class Constructor calling chain super keyword Overriding methods (most important) Hiding methods Hiding fields Type casting

More information

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U C A N A D I A N I N T E R N A T I O N A L S C H O O L O F H O N G K O N G INHERITANCE & POLYMORPHISM P2 LESSON 12 P2 LESSON 12.1 INTRODUCTION inheritance: OOP allows a programmer to define new classes

More information

COSC252: Programming Languages: Abstraction and OOP. Jeremy Bolton, PhD Asst Teaching Professor. Copyright 2015 Pearson. All rights reserved.

COSC252: Programming Languages: Abstraction and OOP. Jeremy Bolton, PhD Asst Teaching Professor. Copyright 2015 Pearson. All rights reserved. COSC252: Programming Languages: Abstraction and OOP Jeremy Bolton, PhD Asst Teaching Professor Copyright 2015 Pearson. All rights reserved. Copyright 2015 Pearson. All rights reserved. Topics The Concept

More information

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2) Software Paradigms (Lesson 3) Object-Oriented Paradigm (2) Table of Contents 1 Reusing Classes... 2 1.1 Composition... 2 1.2 Inheritance... 4 1.2.1 Extending Classes... 5 1.2.2 Method Overriding... 7 1.2.3

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 26 March 23, 2016 Inheritance and Dynamic Dispatch Chapter 24 Inheritance Example public class { private int x; public () { x = 0; } public void incby(int

More information

Java Fundamentals (II)

Java Fundamentals (II) Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class

More information

PROGRAMMING LANGUAGE 2

PROGRAMMING LANGUAGE 2 31/10/2013 Ebtsam Abd elhakam 1 PROGRAMMING LANGUAGE 2 Java lecture (7) Inheritance 31/10/2013 Ebtsam Abd elhakam 2 Inheritance Inheritance is one of the cornerstones of object-oriented programming. It

More information

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes Inheritance Inheritance is the mechanism of deriving new class from old one, old class is knows as superclass and new class is known as subclass. The subclass inherits all of its instances variables and

More information

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2 CITS2200 Data Structures and Algorithms Topic 2 Java Primer Review of Java basics Primitive vs Reference Types Classes and Objects Class Hierarchies Interfaces Exceptions Reading: Lambert and Osborne,

More information

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources. Java Inheritance Written by John Bell for CS 342, Spring 2018 Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources. Review Which of the following is true? A. Java classes may either

More information

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

IST311. Advanced Issues in OOP: Inheritance and Polymorphism IST311 Advanced Issues in OOP: Inheritance and Polymorphism IST311/602 Cleveland State University Prof. Victor Matos Adapted from: Introduction to Java Programming: Comprehensive Version, Eighth Edition

More information

VIRTUAL FUNCTIONS Chapter 10

VIRTUAL FUNCTIONS Chapter 10 1 VIRTUAL FUNCTIONS Chapter 10 OBJECTIVES Polymorphism in C++ Pointers to derived classes Important point on inheritance Introduction to virtual functions Virtual destructors More about virtual functions

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

More information

ECE 3574: Dynamic Polymorphism using Inheritance

ECE 3574: Dynamic Polymorphism using Inheritance 1 ECE 3574: Dynamic Polymorphism using Inheritance Changwoo Min 2 Administrivia Survey on class will be out tonight or tomorrow night Please, let me share your idea to improve the class! 3 Meeting 10:

More information

C++ Programming: Polymorphism

C++ Programming: Polymorphism C++ Programming: Polymorphism 2018 년도 2 학기 Instructor: Young-guk Ha Dept. of Computer Science & Engineering Contents Run-time binding in C++ Abstract base classes Run-time type identification 2 Function

More information

Decaf Language Reference Manual

Decaf Language Reference Manual Decaf Language Reference Manual C. R. Ramakrishnan Department of Computer Science SUNY at Stony Brook Stony Brook, NY 11794-4400 cram@cs.stonybrook.edu February 12, 2012 Decaf is a small object oriented

More information

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance?

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance? CS6501 - Internet programming Unit- I Part - A 1 Define Java. Java is a programming language expressly designed for use in the distributed environment of the Internet. It was designed to have the "look

More information

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University Day 3 COMP 1006/1406A Summer 2016 M. Jason Hinek Carleton University today s agenda assignments 1 was due before class 2 is posted (be sure to read early!) a quick look back testing test cases for arrays

More information

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner. HAS-A Relationship Association is a relationship where all objects have their own lifecycle and there is no owner. For example, teacher student Aggregation is a specialized form of association where all

More information

The SPL Programming Language Reference Manual

The SPL Programming Language Reference Manual The SPL Programming Language Reference Manual Leonidas Fegaras University of Texas at Arlington Arlington, TX 76019 fegaras@cse.uta.edu February 27, 2018 1 Introduction The SPL language is a Small Programming

More information

.Net Technologies. Components of.net Framework

.Net Technologies. Components of.net Framework .Net Technologies Components of.net Framework There are many articles are available in the web on this topic; I just want to add one more article over the web by explaining Components of.net Framework.

More information

Atelier Java - J1. Marwan Burelle. EPITA Première Année Cycle Ingénieur.

Atelier Java - J1. Marwan Burelle.  EPITA Première Année Cycle Ingénieur. marwan.burelle@lse.epita.fr http://wiki-prog.kh405.net Plan 1 2 Plan 3 4 Plan 1 2 3 4 A Bit of History JAVA was created in 1991 by James Gosling of SUN. The first public implementation (v1.0) in 1995.

More information

OBJ. ORI.& MULT. PROG., M.C.Q. BANK, FOR UNIT -2, SECOND YEAR COMP. ENGG. SEM-4, 2012 PATTERN, U.O.P. UNIT-2

OBJ. ORI.& MULT. PROG., M.C.Q. BANK, FOR UNIT -2, SECOND YEAR COMP. ENGG. SEM-4, 2012 PATTERN, U.O.P. UNIT-2 UNIT-2 Syllabus for Unit-2 Introduction, Need of operator overloading, overloading the assignment, binary and unary operators, overloading using friends, rules for operator overloading, type conversions

More information

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Introduction History, Characteristics of Java language Java Language Basics Data types, Variables, Operators and Expressions Anatomy of a Java Program

More information

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Chapter 6 Inheritance Extending a Class

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat Chapter 6 Inheritance Extending a Class Chapter 6 Inheritance Extending a Class Introduction; Need for Inheritance; Different form of Inheritance; Derived and Base Classes; Inheritance and Access control; Multiple Inheritance Revisited; Multilevel

More information