Deccansoft Software Services - MS.NET C# and VB.NET

Similar documents
Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Basic Object-Oriented Programming in Java

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Java Interview Questions and Answers

C++ INTERVIEW QUESTIONS

Description of Class Mutation Mutation Operators for Java

Many applications consist of one or more classes, each containing one or more methods. If you become part of a development team in industry, you may

Java CPD (I) Frans Coenen Department of Computer Science

CS 111 Classes I 1. Software Organization View to this point:

Compile-time type versus run-time type. Consider the parameter to this function:

Java Programming Language

CIS 190: C/C++ Programming. Polymorphism

VB.NET - CLASSES & OBJECTS

D06 PROGRAMMING with JAVA

AP Computer Science Java Subset

Chapter 13 - Inheritance

Advanced Data Structures

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

OpenCL Static C++ Kernel Language Extension

Getting Started with the Internet Communications Engine

Introduction to Object-Oriented Programming

CS506 Web Design and Development Solved Online Quiz No. 01

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

Java Programming Fundamentals

Yosemite National Park, California. CSE 114 Computer Science I Inheritance

Fundamentals of Java Programming

Programming Languages Featherweight Java David Walker

CSE 1020 Introduction to Computer Science I A sample nal exam

SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

1 bool operator==(complex a, Complex b) { 2 return a.real()==b.real() 3 && a.imag()==b.imag(); 4 } 1 bool Complex::operator==(Complex b) {

C++FA 5.1 PRACTICE MID-TERM EXAM

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Part I. Multiple Choice Questions (2 points each):

VB.NET INTERVIEW QUESTIONS

Crash Course in Java

Visual Web Development

Moving from CS 61A Scheme to CS 61B Java

Object-Oriented Programming Lecture 2: Classes and Objects

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

CS193j, Stanford Handout #10 OOP 3

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

VB.NET Programming Fundamentals

History OOP languages Year Language 1967 Simula Smalltalk

Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT - BCNS/05/FT - BIS/06/FT - BIS/05/FT - BSE/05/FT - BSE/04/PT-BSE/06/FT

INTRODUCTION TO C# 0 C# is a multi-paradigm programming language which is based on objectoriented and component-oriented programming disciplines.

public static void main(string[] args) { System.out.println("hello, world"); } }

J a v a Quiz (Unit 3, Test 0 Practice)

Classes and Pointers: Some Peculiarities (cont d.)

Glossary of Object Oriented Terms

Inheritance, overloading and overriding

Symbol Tables. Introduction

Konzepte objektorientierter Programmierung

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

JavaScript. JavaScript: fundamentals, concepts, object model. Document Object Model. The Web Page. The window object (1/2) The document object

Object-Oriented Programming: Polymorphism

JAVA - EXCEPTIONS. An exception can occur for many different reasons, below given are some scenarios where exception occurs.

Inheritance in Programming Languages

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Code Contracts User Manual

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

I. INTRODUCTION. International Journal of Computer Science Trends and Technology (IJCST) Volume 3 Issue 2, Mar-Apr 2015

Chapter 5 Names, Bindings, Type Checking, and Scopes

13 Classes & Objects with Constructors/Destructors

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

ICOM 4015: Advanced Programming

Web Services in.net (1)

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Sources: On the Web: Slides will be available on:

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

JAVA - INHERITANCE. extends is the keyword used to inherit the properties of a class. Below given is the syntax of extends keyword.

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

The C Programming Language course syllabus associate level

Chapter 4 OOPS WITH C++ Sahaj Computer Solutions

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Java Application Developer Certificate Program Competencies

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

Course Name: ADVANCE COURSE IN SOFTWARE DEVELOPMENT (Specialization:.Net Technologies)

Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A

Facebook Twitter YouTube Google Plus Website

More on Objects and Classes

Constructor, Destructor, Accessibility and Virtual Functions

Short Introduction to the Concepts of Programming in Java Overview over the most important constructs

Contents. 9-1 Copyright (c) N. Afshartous

Basic Logic Gates. Logic Gates. andgate: accepts two binary inputs x and y, emits x & y. orgate: accepts two binary inputs x and y, emits x y

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

Tutorial on Writing Modular Programs in Scala

JAVA - METHODS. Method definition consists of a method header and a method body. The same is shown below:

What is Java? Applications and Applets: Result of Sun s efforts to remedy bad software engineering practices

WRITING DATA TO A BINARY FILE

Class 16: Function Parameters and Polymorphism

Install Java Development Kit (JDK) 1.8

Basics of C++ and object orientation in OpenFOAM

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Transcription:

Agenda 1. Introduction to 2. Constructors & 3. Type casting of Reference Types 4. Static and dynamic binding 5. Abstract classes Table of Contents OVERVIEW 2 STATIC AND DYNAMIC BINDING 6 ABSTRACT CLASSES AND METHODS 8 SYSTEM.OBJECT CLASS 10 1

depends upon is a relationship. For example: Car is a Vehicle Faculty is a Person Student is a Person Mango is a Fruit Chair is a Furniture Scientific Calculator is a Calculator General syntax: class CParent class CChild : CParent Overview Constructors and : 1. Create a New Project (ConsoleApplication1) 2. Add the following code to the file in that project. Program to show Option Strict On Public Class CParent Public PubA As Integer Private PriA As Integer Protected ProA As Integer Sub New() Sub New(ByVal a As Integer, ByVal b As Integer, ByVal c As Integer) Me.New() Me.PriA = a Me.ProA = b Me.PubA = c Public Class CChild Inherits CParent Public pubb As Integer Sub New() 'Will call base class constructor Sub New(ByVal a As Integer, ByVal b As Integer, ByVal c As Integer, ByVal d As Integer) MyBase.New(a, b, c) Me.pubB = d Public Sub Foo() Dim p As New CParent Dim c As New CChild ProA = 10 c.proa = 10 'p.proa = 10 ' Compilation Error because "p" is of type Parent. 2

Public Class Program Shared Sub Main(ByVal args() As String) Dim b As CChild b = New CChild(1, 2, 3, 4) b.foo() Code: 5.1 VB Program to show using System; public class CParent public int PubA; private int PriA; protected int ProA; public CParent() public CParent(int a, int b, int c) : this() this.pria = a; this.proa = b; this.puba = c; public class CChild : CParent public int pubb; public CChild() //First calls parent class constructor. public CChild(int a, int b, int c, int d) : base(a, b, c) //this.pria = a; this.proa =b; this.puba = c; this.pubb = d; public void Foo() CParent p = new CParent(); CChild c = new CChild(); ProA = 10; //Allowed c.proa = 10; //Allowed //p.proa = 10; //Compilation Error because p is of type parent. class Program static void Main(string[] args) CChild b; b = new CChild(1, 2, 3, 4); 3

b.foo(); Code: 5.1 C# Notes: Protected members are accessible only within the class and in derived classes and are not accessible to nonderived classes The protected member of parent class cannot be accessed in a child class method using the reference variable of type parent. For example refer to Foo method in the above CChild class(p.proa = 10) When an object of child class is created all the data members of the parent class and child class are allocated memory irrespective of their access specifier i.e. public or private or protected. Whenever an object of child class is created, even though the child class constructor is visited first, it s the parent class constructor which is executed first. This is because the child class constructor can then override the code already executed in parent class constructor. Every child class constructor by default first calls default constructor of parent class. Using base in C# (MyBase in VB) and with appropriate arguments a child class constructor can make an explicit call any other constructor of parent class. The order of visiting constructor is child class first and then parent because the child class constructor if required can pass data to the parent class constructor using base It is recommended that a child class constructor always pass data to the parent class constructor so that the parent class constructor can initialize the data members of the parent class and the child class constructor remains with initializing only its own data members. If the parent class doesn t have default constructor, then every child class constructor must explicitly link to any other constructor of the parent class. The order of execution of destructor is child first and then parent which is reverse order of execution of constructor. 4

Type Casting of Reference Types CParent p; CChild c; p = new CChild(); //Valid c = new CParent(); //Invalid and Compilation Error. A reference variable of type parent can refer to an object of child class because all the members which the reference variable can access exist in memory when the object is of child class. A reference variable of child cannot refer to an object of parent class because the child class members that the reference variable can access do not exist in memory when the object is of parent class. Note: Using a reference variable of type parent, child class members cannot be accessed even if the object is of child class. CParent p; CChild c; p = c //is Valid Does Implicit casting because the object to which c can refer to is only of type CChild (child class) and p can also refer to that object. c = p // is invalid because p can refer to an object of type CParent and CChild but c cannot refer to an object of type CParent, hence the compiler for such statements give an error. p = new CChild () ; c = p; //is still not allowed c = (CChild) p; //Explicit Casting is valid but if p refer to an object of type CParent then at runtime InvalidCastException is thrown CParent p = new CChild() / CParent(); CChild c = p as CChild; // as is an operator Console.WriteLine(c == null); as Operator: if p is referring to an object of type CChild or any of its subclass then the reference is assigned to c otherwise it assigns null to c (it doesn t throw InvalidCastException) Is Operator: o if (p is CChild) The above condition is true only if p is referring to an object of class CChild or any of its subclass. "??" Operator: object y = x?? z; // y = x, unless x is null, in which case y = z. 5

Static and Dynamic Binding Virtual methods are dynamically bound i.e., the actual method called would be decided at runtime and the decision is based on the object to which the reference variable invoking the method is referring to. Methods not declared as virtual are statically bound i.e., the actual method invoked would be decided at compile time and is based on purely the data type of the reference variable invoking the method irrespective of the object the reference variable is referring to. CParent p; -------- virtual virtual CChild c; new new override p = new CChild(); p.foo(); Static Dynamic Dynamic Compile Runtime Runtime DataType Object Type Object Type CParent CParent CChild using reference variable of type parent - Child class method can execute only if 1. Child class object is created 2. Child class overrides parent class method. If the class of the reference variable has the method declared as virtual then it is dynamic binding otherwise its static binding. Static binding gives better performance than dynamic binding. Program for using Overrideable, Overrides Option Strict On Public Class CParent Public Overridable Sub Foo() Console.WriteLine("CParent") Code: 5.2 VB Class CChild Inherits CParent Public Overrides Sub Foo() Console.WriteLine("CChild") Public Class Program Shared Sub Main(ByVal args() As String) Dim a As CParent a = New CChild() a.foo() Program for using Virtual, Override class CParent public virtual void Foo() Console.WriteLine("CParent"); class Program static void Main(string[] args) CParent a = new CChild(); a.foo(); class CChild : CParent public override void Foo() Console.WriteLine("CChild"); 6

Code: 5.2 C# Try the above program with and without virtual and override keywords in both CParent and CChild classes. If the object is of child class and the child class overrides the method only then the child class method is executed. Otherwise it will always execute parent class method. Only virtual methods or overridden methods of parent class can be overridden in the child class. A method declared as new can also be declared as virtual new and such methods shadows the parent class method but can be overridden in the child class if needed. Note: Field members are always statically binded at compile time based on the Data Type of the reference variable accessing the member. Instance variables cannot be declared as virtual in parent class and thus if a variable with same name is declared in the child class then it should be declared as new. A class declared as sealed cannot be inherited. A method declared as sealed cannot be overridden in the child class. All possible combinations of virtual, new, override and sealed keywords. Parent -- --- -- virtual virtual virtual virtual virtual virtual new new new new override Child new virtual virtual new virtual virtual override override sealed GrandChild new new override new new override new override new Parent p; p = new GrandChild() p.foo() Static Static Static Dynamic Dynamic Dynamic Dynamic Dynamic Dynamic Which method is executed. Parent Parent Parent Parent Parent Parent Child GrandChild Child 7

Abstract Classes and Methods 1. An abstract method is a method in which declaration is provided but implementation is not. 2. A class with one or more methods declared as abstract must be declared as abstract and such a class cannot be instantiated because its behavior is incomplete. 3. A class that inherits the abstract class must override all the abstract members of the parent class, if not it should also be declared as abstract. Abstract = Pure Virtual 4. A class can be declared as abstract even without an abstract member and such a class cannot be instantiated. 5. A class which is not abstract is called as Concrete Class. (concrete is not a keyword) 6. An abstract class can have all types of members which a concrete class can have including constructor, destructor, static members etc (additionally it can have abstract members which a concrete class cannot have) 7. A sealed class cannot have abstract methods. Create a New Console Application and add the following code to the various files added to that project. Using MustInherit(Abstract version of C#) MustInherit Class Figure Public Dimension As Integer Public MustOverride Function Area() As Double Public MustOverride Function Perimeter() As Double Class Square Inherits Figure Public Overrides Function Area() As Double Return Dimension * Dimension End Function Public Overrides Function Perimeter() As Double Return 4 * Dimension End Function Class Circle Inherits Figure Public Overrides Function Area() As Double Return Math.PI * Dimension * Dimension End Function Public Overrides Function Perimeter() As Double Return 2 * Math.PI * Dimension End Function Class Program Sub Main() Dim fig As Figure = New Square() fig.dimension = 10 Console.WriteLine(fig.Area()) Console.WriteLine(fig.Perimeter()) Code: 5.3 VB 8

Using Abstract: using System; abstract class Figure public int Dimension; public abstract double Area(); public abstract double Perimeter(); class Square : Figure public override double Area() return Dimension * Dimension; public override double Perimeter() return 4 * Dimension; class Circle : Figure public override double Area() return Math.PI * Dimension * Dimension; public override double Perimeter() return 2 * Math.PI * Dimension; class Program static void Main() Figure fig = new Square(); // or Circle(); fig.dimension = 10; Console.WriteLine(fig.Area()); Console.WriteLine(fig.Perimeter()); Code: 5.3 C# Output: If Object is of type Square, then the Area and Perimeter of Square is printed. Similarly if the object is of type Circle then Area and Perimeter of Circle is printed. 9

System.Object Class Every class in.net is inherited from System.Object class. Thus the functionality in Object class is available to all the objects in.net. Also the reference variable of type System.Object can refer to instance/object of any class in.net Methods in Object class: 1. bool Equals(object obj) // Compares the current object reference with obj and returns true if both are referring to the same object otherwise returns false. 2. System.Type GetType() //returns the Type instance for the current objects class. 3. int GetHashCode() //return a unique number using which CLR identifies the current object. 4. string ToString() //return the class name of the current object. Note: The GetHashCode() method should reflect the Equals logic; the rules are: 1. if two things are equal (Equals(...) == true) then they must return the same value for GetHashCode() 2. if the GetHashCode() is equal, it is not necessary for them to be the same; this is a collision, and Equals will be called to see if it is a real equality or not. class Point : Object public int X, Y; public override string ToString() return X + " " + Y; public override bool Equals(object obj) Point p = (Point)obj; return (this.x == p.x) && (this.y == p.y); public override int GetHashCode() int hashx = X.GetHashCode(); int hashy = Y.GetHashCode(); int hash = 10; hash = (hash * 7) + hashx; hash = (hash * 7) + hashy; return hash; class Program static void Main(string[] args) Point pt1 = new Point() X = 11, Y = 10 ; Console.WriteLine(pt1.ToString()); Point pt2 = new Point() X = 11, Y = 10 ; Console.WriteLine(pt1.Equals(pt2)); Console.WriteLine(pt1.GetHashCode() + " " + pt2.gethashcode()); 10

Summary: Type tp1 = pt1.gettype(); Type tp2 = pt2.gettype(); Console.WriteLine(tp1 == tp2); Object ob = new Object(); Console.WriteLine(ob); In this article, we have studied inheritance and use of constructors along with it. Static and dynamic binding with the methods and Abstract classes and methods are also covered in this topic. 11