Wednesday, 13 November 2013

Inheritance & polymorphism





l Inheritance
  1. Inheritance allows a software developer to derive a new  class from an existing one.
  2. The existing class is called the parent, super, or base class.
  3. The derived class is called a child or subclass.
  4. The child inherits characteristics of the parent.
  5. Methods and data defined for the parent class.
  6. The child has special rights to the parents methods and data.
  7. Public access like any one else
  8. Protected access available only to child classes (and their descendants).
  9. The child has its own unique behaviors and data.
     
                 Base class &  Derived class


        class BaseClass
        {
        class DerivedClass : BaseClass
        {
        }
        A child class inherits the methods and data defined for the parent class; however, whether a data or method member of a parent class is accessible in the child class depends on the visibility modifier of a member.

        Private
        Variables and methods declared with private visibility are not accessible in the child class
        However, a private data member defined in the parent class is still part of the state of a derived class.
        Public

        Variables and methods declared with public visibility are accessible; but public variables violate our goal of encapsulation

        Protected
        There is a third visibility modifier that helps in inheritance situations: protected

        Variables and methods declared with protected visibility in a parent class are only accessible by a child class or any class derived from that class

        Some languages, e.g., C++, allow Multiple inheritance, which allows a class to be derived from two or more classes, inheriting the members of all parents.
        C# and Java support single inheritance, meaning that a derived class can have only one parent class


        Override
        A child class can override the definition of an inherited method in favor of its own
        That is, a child can redefine a method that it inherits from its parent
        The new method must have the same signature as the parent's method, but can have a different implementation.
        The type of the object executing the method determines which version of the method is invoked


        Inheritance is transitive
        An inherited member is continually passed down the line.Good class design puts all common features as high in the hierarchy as is reasonable. Avoids redundant code.

        References and Inheritance 
        An object reference can refer to an object of its class, or to an object of any class derived from it by inheritance.

        For example, if the Holiday class is used to derive a child class called Christmas, then a Holiday reference can be used to point to a Christmas object


        Holiday day;
        day=new Holiday();
        day=new Christmas();

        Dynamic Binding 
        A polymorphic reference is one which can refer to different types of objects at different times. It morphs!

        The type of the actual instance, not the declared type, determines which method is invoked.


        Polymorphic references are therefore resolved at run-time, not during compilation.
        This is called dynamic binding.



        Suppose the Holiday class has a method called Celebrate, and the Christmas class redefines it (overrides it).Now consider the following invocation:

        day.Celebrate();
        If day refers to a Holiday object, it invokes the Holiday version of Celebrate;  if it refers to a Christmas object, it invokes the Christmas version



        virtual, override and new
        C# requires that all class definitions communicate clearly their intentions.

        The keywords virtual, override and new provide this communication.


        If a base class method is going to be overridden it should be declared virtual.


        A derived class would then indicate that it indeed does override the method with the override keyword


        If a derived class wishes to hide a method in the parent class, it will use the new keyword.
        This should be avoided



        Widening and Narrowing

        Assigning an object to an ancestor reference is considered to be a widening conversion, and can be performed by simple assignment

        Holiday day = new Christmas();


        Assigning an ancestor object to a reference can also be done, but it is considered to be a narrowing conversion and must be done with a cast:


        Christmas christ = new Christmas();
        Holiday day = christ;
        Christmas christ2 = (Christmas)day;



        Question and Answer
        1.How to prevent  a class being inherited ?
         
        Sealed

        sealed class A
        {
        public int A,
        public int B
        } No class can be inherited from class A

        2.When you are using shadowing if you want to access the base class method with derived class how can you access it?

        public class Baseclass
        {
             public void Method1()
            {
            string a="Base Method" ;
             }


        public class Deriveclass:BaseClass
        {
           public new void Methaod1()
            {
             string a="Derive Methaod";
            }


        public class testApp
        {
            public static void main()
             {
              DeriveClass deriveObj=new DerideCalss();
                  BaseClass obj2=(BaseClass)deriveclass;
                  obj2.Method1() 
            }
        }

        3)What is the different between Class & object

        Class:User defined datatype, method,property,abstarct charateistic
        Object :instance of a class,which is created at rutime 

        4)Overloading and overrriding

        overloading:more than one method with same name 
        overriding:Change behaviour of class in derive class using dynamic polymorphism


        5)What is the difference between shadowing and overriding?

        6) Common interface in C#

                 System.Data.IDataAdopter
                 System.Data.IDataParameter
                 System.Data.IDataReader
                 System.Data.IDataConnection
                 System.Data.IHttpModule


         Common Sealed class in C#

                 System.Data.SqlClient.Sqlcommand
                 System.Data.SqlClient.Sqlconnetion
                 System.Data.SqlClient.SqlDataAdopter         System.Data.SqlClient.SqlconnetionStringBuilder      


        Common abstract class in C#

                System.Data.Common.DbCommand
                System.Data.Common.DbConnection
                System.Data.Common.DbDataReader
                System.Data.Xml.Node 

        System.Data.Xml.Node 

        Common static classes
           
               System.Math
               System.Convert
               System.Net


         
        7.How many types of inheritances are there in C#?
        Ans. There are two types of inheritance in C#.
        a) Interface inheritance : When a class or interface is inheriting from another interface, is called interface inheritance.
        b)Implementation inheritance : When a class is inheriting from another class, is called implementation inheritance.

        8.What is Interface?
        Ans. An interface is used to declare methods, properties, events etc. Interface dose not contain any definitions of these contructs. The class that inherit from interface has to define/implement all the members of that interface.
        A class can inherit from more than one interfaces.

        9.What is Abstract class?
        Ans. An abstract class is a class that cant be instantiated. A class can be abstract if any one of the following occures:
        a) Class is declared as Abstract
        b) class is inherited from another abstract class but not implemented all abstract methods of the base class.
        c) class that has some abstract methods 

                public abstract class SampleClassAbstract
                {
                    public static void DisplayMessage()
                    {
                        Console.WriteLine("Static Method within Abstract Class Executed");
                        
                    }           
        
                }
         

        10)Static Classes and Static Class Members
        A static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself

        public static class TemperatureConverter
            {
                public static double CelsiusToFahrenheit(string temperatureCelsius)
                {
                    // Convert argument to double for calculations. 
                    double celsius = Double.Parse(temperatureCelsius);
        
                    // Convert Celsius to Fahrenheit. 
                    double fahrenheit = (celsius * 9 / 5) + 32;
        
                    return fahrenheit;
                }
        
                public static double FahrenheitToCelsius(string temperatureFahrenheit)
                {
                    // Convert argument to double for calculations. 
                    double fahrenheit = Double.Parse(temperatureFahrenheit);
        
                    // Convert Fahrenheit to Celsius. 
                    double celsius = (fahrenheit - 32) * 5 / 9;
        
                    return celsius;
                }
            }

        public static class TemperatureConverter
            {
                public static double CelsiusToFahrenheit(string temperatureCelsius)
                {
                    // Convert argument to double for calculations. 
                    double celsius = Double.Parse(temperatureCelsius);
        
                    // Convert Celsius to Fahrenheit. 
                    double fahrenheit = (celsius * 9 / 5) + 32;
        
                    return fahrenheit;
                }
        
                public static double FahrenheitToCelsius(string temperatureFahrenheit)
                {
                    // Convert argument to double for calculations. 
                    double fahrenheit = Double.Parse(temperatureFahrenheit);
        
                    // Convert Fahrenheit to Celsius. 
                    double celsius = (fahrenheit - 32) * 5 / 9;
        
                    return celsius;
                }
            }
        
            class TestTemperatureConverter
            {
                static void Main()
                {
                    Console.WriteLine("Please select the convertor direction");
                    Console.WriteLine("1. From Celsius to Fahrenheit.");
                    Console.WriteLine("2. From Fahrenheit to Celsius.");
                    Console.Write(":");
        
                    string selection = Console.ReadLine();
                    double F, C = 0;
        
                    switch (selection)
                    {
                        case "1":
                            Console.Write("Please enter the Celsius temperature: ");
                            F = TemperatureConverter.CelsiusToFahrenheit(Console.ReadLine());
                            Console.WriteLine("Temperature in Fahrenheit: {0:F2}", F);
                            break;
        
                        case "2":
                            Console.Write("Please enter the Fahrenheit temperature: ");
                            C = TemperatureConverter.FahrenheitToCelsius(Console.ReadLine());
                            Console.WriteLine("Temperature in Celsius: {0:F2}", C);
                            break;
        
                        default:
                            Console.WriteLine("Please select a convertor.");
                            break;
                    }
        
                    // Keep the console window open in debug mode.
                    Console.WriteLine("Press any key to exit.");
                    Console.ReadKey();
                }
            }
            /* Example Output:
                Please select the convertor direction
                1. From Celsius to Fahrenheit.
                2. From Fahrenheit to Celsius.
                :2
                Please enter the Fahrenheit temperature: 20
                Temperature in Celsius: -6.67
                Press any key to exit.
             */
        The static member is callable on a class even when no instance of the class has been created. The static member is always accessed by the class name, not the instance name

        public class Automobile
        {
            public static int NumberOfWheels = 4;
            public static int SizeOfGasTank
            {
                get
                {
                    return 15;
                }
            }
            public static void Drive() { }
            public static event EventType RunOutOfGas;
        
            // Other non-static fields and properties...
        }
         
        11)Can you declare a private class in a namespace ?
         The classes in a namespace are internal, by default. However, you can 
         explicitly declare them as public only and not as private, protected, or protected 
         internal. The nested classes can be declared as private, protected, or  
         protected internal.

Friday, 8 November 2013

SQL Query

1) Delete , joining two tables

DELETE a.*, b.* 
FROM tbl_member a 
INNER JOIN tbl_member_details b 
ON b.member_id = a.member_id
WHERE a.roll_no>3
 
2)Update , joining two tables
 
UPDATE  a
SET a.Name=b.PName 
FROM tbl_member a  
INNER JOIN tbl_member_deatils b
ON a.id=b.pid
 
3)Common Table Expression ,Cross Table Query
 
WITH CTES
AS
(
SELECT id,pid,Name from tbl_member
UNION ALL 
SELECT a.id,b.pid,c.Name from tbl_member a
INNER JOIN tbl_member b ON a.id=b.pid
)
SELECT * FROM CTES
 
 
4)Function Returns Table
 

CREATE FUNCTION  Function_Returns_Table(@complaiceid INT)
RETURNS @Return_table TABLE 
(
@complanceid INT, 
@complancename VARCHAR(2000)
)
AS
BEGIN
INSERT INTO @Return_table (@complanceid ,@complancename )
SELECT complanceid ,complancename FROM tbl_member_complance
 
WHERE  
complanceid >@complaiceid
 
RETURN
END 
 
5)Comma Deliminated Sql Output
 
 DECLARE @output VARCHAR(MAX)
 SET @output='' 
 SELECT @output=@output+(CASE @output WHEN '' THEN '' ELSE  ',' END)+compliance_name FROM tbl_sref_member_compliance
 PRINT @output
 
 
6)Clustered and Non-Clustered Index
http://www.codeproject.com/Articles/173275/Clustered-and-Non-Clustered-Index-in-SQL-2005 
 
 

8)Find Nth Highest Value from a Table
 
SELECT TOP 1 marks
FROM  
(
SELECT DISTINCT TOP n marks
FROM tbl_students
ORDER BY marksDESC
) a
ORDER BY marks
 
9) SQL Optimization
 
a)sql query  becomes faster if column name is used instead of *
 
slower 
Select * from Student_table
 
Faster 
Select Student_name from Student Table

b)To store large binary object , use file group instead on file
 
c) Try to write minimised number of sub query
 
d) Use "Exists" operator instead of "In"

Slower
Select * from tbl_student
  where id in (Select id from tbl_student where roll_no>5)

Faster
Select * from tbl_student 
  where exists (Select id from tbl_student where roll_no>5)
 
10) sp_executesql
Executes a Transact-SQL statement or batch that can be reused many times .

for example

Declare @class_id INT,@param INT
sp_executesql sp_stydebt @class_id ,@param  OUTPUT
 
12) Select Top N from Table
 
DECLARE  @MyTable table (Name varchar(200),salary decimal(18,2))

INSERT INTO @MyTable(Name,salary)
VALUES('AYAN',200),('SAYAN',300),('Jatin',250),('Jatin lal',400),('Soumay',280)


select * from @MyTable ;

WITH ABC AS 
(
 SELECT salary , Name ,
 ROW_NUMBER() OVER (ORDER BY salary) AS 'Row_Number'
 FROM @MyTable  
)
SELECT * FROM ABC WHERE Row_Number=N
 

 
13) INNER JOIN AND CROSS JOIN
 
    Inner join only results of matching records..for example we have created 
table A and B...
Results is                                                                                   










Cross Join result all combination of records irrespective of any matching records















Result is
 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 14)Common Table Expression
  http://www.codeproject.com/Articles/265371/Common-Table-Expressions-CTE-in-SQL-SERVER 
 
 
 15)Another PIVOT EXample
 
 
 
 
 
 
  
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16)Row_Number Over 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17)Find The N Th highest number
Here N=5 
 
 
 18) How to show only even rows ?
 
SELECT * FROM 
( 
 SELECT role_id,
 role_name,
 ROW_NUMBER() OVER(ORDER BY role_id DESC) AS 'RowNumber' 
        FROM tbl_sref_app_role
) X where (RowNumber % 2) = 0
ORDER BY role_id 
 
 
 19) Find the n th highest number
  
    select max(member_id) from tbl_event_roster

    --nth highest

   select top 1 member_id from 
   (
    select top 5 member_id from tbl_event_roster order by member_id desc
   ) a
   order by a.member_id desc

   --
   with  a (member_id)
   as 
   (
     select top 10 member_id from tbl_event_roster order by member_id desc
   ) 
   select top 6 member_id from a order by member_id desc

 
 20)CUBE
 
 SELECT  i.shif,
         i.location,
         i.bin, 
  CASE GROUPIN_ID(i.shif,i.location,i.bin )
   WHEN 1 THEN 'Shelf/Location Total'
   WHEN 2 THEN 'Shelf/Bin Total'
   WHEN 3 THEN 'Shelf Total'
   WHEN 4 THEN 'Location Bin Total'
   WHEN 5 THEN 'Location Total'
   WHEN 6 THEN 'Bin Total'
   WHEN 7 THEN 'Grand Total'
   ELSE 'regular row'
  END,
  SUM(i.quantity) AS Total
FROM Production
GROUP BY CUBE(i.shif,i.location,i.bin)
ORDER BY i.shif,
         i.location,
         i.bin


SELECT  member_id,
  role_id,
  reference_id,
  SUM(reference_type_id)
  FROM tbl_user_role
  GROUP BY CUBE(member_id,role_id,reference_id)
  ORDER BY member_id,role_id,reference_id
 
 21)PERCENT
 
 SELECT TOP (5) PERCENT
              member_id FROM 
              tbl_user_role

 22)UNPIVOT
 
SELECT Employee_ID,
       PhoneType,
       PhoneValue 
       FROM Contact C
UNPIVOT
(
PhoneValue FOR PhoneType IN ([Ph1],[Ph2],[Ph3],[Ph4],[Ph5])
)AS P 
 
23) CROSS ApplY
 
CREATE TABLE Company 
(
    companyId int identity(1,1),
    companyName varchar(100),
    zipcode varchar(10) ,
    constraint PK_Company primary key (companyId)
)
GO

CREATE TABLE Person 
(
    personId int identity(1,1),
    personName varchar(100),
    companyId int ,
    constraint FK_Person_CompanyId foreign key (companyId) references dbo.Company(companyId),
    constraint PK_Person primary key (personId)
)
GO

INSERT Company
SELECT 'ABC Company', '19808' 
UNION
SELECT 'XYZ Company', '08534' 
UNION
SELECT '123 Company', '10016'


INSERT Person
SELECT 'Alan', 1 
UNION
SELECT 'Bobby', 1 
UNION
SELECT 'Chris', 1 
UNION
SELECT 'Xavier', 2 
UNION
SELECT 'Yoshi', 2 
UNION
SELECT 'Zambrano', 2 
UNION
SELECT 'Player 1', 3 
UNION
SELECT 'Player 2', 3 
UNION
SELECT 'Player 3', 3 


SELECT *
FROM Person p
CROSS APPLY
(
    SELECT *
    FROM Company c
    WHERE p.companyid = c.companyId
) Czip
 
21)
DECLARE @quotedcountrynames NVARCHAR(MAX)

SET @quotedcountrynames = STUFF((
            SELECT DISTINCT ',' + QUOTENAME(CustomerCountry)
            FROM Customer
            FOR XML PATH('')
                ,TYPE
            ).value('.', 'NVARCHAR(MAX)'), 1, 1, '')

PRINT @quotedcountrynames
output
[Dave],[Johny],[Tommy] 

বাঙালির বেড়ানো সেরা চারটি ঠিকানা

  বাঙালি মানে ঘোড়া পাগল | দু একদিন ছুটি পেলো মানে বাঙালি চলল ঘুরতে | সে সমুদ্রই হোক , পাহাড়ি হোক বা নদী হোক। বাঙালির ...