Setting up a hidden service is not difficult, despite all the
headlines lately of major busts and it often being referred to as the
“dark net”. In this quite short guide, we have the very simple aim of
setting up a hidden service to serve up static HTML pages using Nginx. I
could write a whole thesis on why using Nginx is superior to Apache for
this use case, but for now I shall keep it simply to “it’s simpler and
more secure”.
This guide is in no way meant to be exhaustive here.
This is not a hardening guide. This is here to get you started with
your first hidden service. You can rent a VPS to do this, or you can
even host it on a virtual machine on your computer (it makes no
difference – really).
Now I intend for this to be as accessible as
possible but there is a very small set of requirements. I don’t believe
this will rule out anyone who is intending on setting up a basic hidden
service.
Requirements:
– Know how to SSH into a VPS/server
– Running Debian 7 (Wheezy) 64 bit
What
I would recommend for your Debian installation is at least 256 MB RAM, 1
core or more and 8Gb or more hard drive space. If you are installing
Debian on your local machine, you do not need to install anything but
the very base files. Everything you need in this guide will be
installed as we go along. However for the purpose of this guide, I will
act like you are using a basic VPS. Commands will be highlighted in purple & configuration entries in blue.
Contents at a glance:
1. Connect to the server
2. Retrieve some packages
3. Setup user
4. Add user to sudoers & basic SSH configuration
5. Download & install Tor
6. torrc file configuration & hidden service key generation
7. Nginx installation & configuration
1. Connect to the server
To SSH into your VPS, it is very simple. If you have a Linux computer, go to the command line and type:
ssh root@<ip-address-here>
This will prompt you to enter the root password and once you have entered it, you should be logged in as root!
2. Retrieve some packages
As root, type the following command:
apt-get update && apt-get upgrade && apt-get install sudo nano
You will then be told how much additional space is required to install
the above packages after the package list has been updated, and the
updates downloaded. Type “Y” and hit enter to accept and install them.
3. Setup user
It is recommended you never run any software as root when you can avoid it. So as root type:
adduser user
This
will add a new user called “user” (feel free to replace this with
whatever you want). You may be asked for various other bits of
information like full name, office number etc, you can just hit enter to
skip them. At the end you will be asked “Is the information correct?”,
again type Y and hit enter to confirm.
4. Add user to sudoers & basic SSH configuration
For
those not familiar with Linux systems, sudo is the package which
enables users to obtain superuser capabilities just like root for
certain tasks. This allows a user to login to the system and manage it
without needing to switch to root. To add your new user to the sudo
list, type the following as root:
sudo adduser user sudo
Now
“user” has been added to the sudoers list. Now we should make some very
quick and basic changes to your sshd process to block off anyone trying
to SSH into your VPS as root and a simple technique to stop brute force
SSH attempts.
To open up your sshd configuration, type:
nano /etc/ssh/sshd_config
The
first option to find is “Port 22” which should be near the top of the
file. Change the port “22” to something non-standard, for example 22555,
so the new entry should look like this:
Port 22555
Now
you need to disable root SSH login attempts. Find the option
“PermitRootLogin yes” and change it to “no” so the new entry is as
follows:
PermitRootLogin no
Now as root, reload the SSH service using:
service ssh reload
This
reloads sshd, and your changes should now take effect. Note that in
future when you SSH into your server, you must remember the new port and
login as a user. So for example, if your new user is called “user” and
the port you changed the above setting to is 22555, your new ssh command
is:
ssh -p 22555 user@<ip-address-here>
5. Download & install Tor
The
first and most important thing that must be done is to update the
sources list to the official Tor Project repository. To make this easy
for you, I have reduced this to a single command:
echo
‘deb http://deb.torproject.org/torproject.org wheezy main’ >>
/etc/apt/sources.list && echo ‘deb-src
http://deb.torproject.org/torproject.org wheezy main’ >>
/etc/apt/sources.list && gpg –keyserver keys.gnupg.net –recv
886DDD89 && gpg –export A3C4F0F979CAA22CDBA8F512EE8CBC9E886DDD89
| sudo apt-key add – && apt-get
This means the
official Tor repository is now added to your sources list, and you have
downloaded the official Tor Project keys to your server to
cryptographically ensure the binaries you receive are genuine. Now to
install Tor itself, we want to switch to our newly created user which in
this instance I have called “user”. This can be done by running the
command:
su user
Now to install the Tor binary and the Tor Project keyring, run:
sudo apt-get update && sudo apt-get install tor deb.torproject.org-keyring
Tor is now installed and automatically starts!
6. torrc file configuration & hidden service key generation
The
torrc file is the configuration file Tor reads your options from. The
file is full of information that we don’t currently need, and so I
recommend deleting the existing torrc file and creating a new one. This
can be done using a single quick command:
sudo rm /etc/tor/torrc && sudo nano /etc/tor/torrc
This
should now remove the existing torrc and open a new one up in the nano
file editor. The minimum you will require for running a hidden service
is the following configuration, which can be pasted and saved in the new
file:
DataDirectory /var/lib/tor
HiddenServiceDir /var/lib/tor/hidden_service/
HiddenServicePort 80 127.0.0.1:80
Pressing
Ctrl + X will save the file. Now to generate the hidden service key and
make the Tor process take note of our changes, we should reload the
process:
sudo service tor reload
To
find out what your hidden service key is (also known as the hostname),
use the cat command. Write this hostname down somewhere or copy it to
your clipboard – you will need it in a moment:
sudo cat /var/lib/tor/hidden_service/hostname
The private key can be found at (you don’t need to view this right now, this is for your information only):
/var/lib/tor/hidden_service/private_key
You
can share the hostname key with anyone you want to visit your site. It
should look something like qhzwfy24i22jchdw.onion (this is the one I
generated when testing this tutorial).
7. Nginx installation & configuration
As user, type the following command to install Nginx:
sudo apt-get install nginx
Now we need to make a new directory in /var/www/ for our hidden service site. Use the mkdir command to do this:
sudo mkdir -p /var/www/hidden_service/
Finally, we need to set the permissions for the new folders:
sudo chown -R www-data:www-data /var/www/hidden_service/ && sudo chmod 755 /var/www
So
we can test the setup in a moment, let us generate a quick test index
page, very similar to how we made the new torrc file earlier:
sudo nano /var/www/hidden_service/index.html
In this file, paste the following snippet of HTML code and save the file:
<html>
<head> <title>Hidden Service Success</title>
</head> <body> <h1>Success: You Have Set Up Your
Hidden Service With NGINX</h1> </body> </html>
Now
comes the part where we need to configure Nginx to listen in the
correct place. In Apache, this would be called a Virtual Host but on
Nginx they are known as Server Blocks. To make the new Server Block, we
are going to to use the nano command again:
sudo nano /etc/nginx/sites-available/hidden_service
In
this newly created file, paste the following snippet of information.
Using the hostname you copied earlier to replace qhzwfy24i22jchdw.onion
with your own address:
server {
listen 127.0.0.1:80;
root /var/www/hidden_service/;
index index.html index.htm;
server_name qhzwfy24i22jchdw.onion;
}
Save
and exit this new file. The last step now is to create a symbolic link
between the sites-available directory and sites-enabled directory. In
Apache, we use a2ensite but Nginx does not have such a function, but
instead we can use the following command to form one:
sudo ln -s /etc/nginx/sites-available/hidden_service /etc/nginx/sites-enabled/hidden_service
Finally, restart Nginx for all the new configuration options to take effect:
sudo service nginx restart
That’s it!
You now have your own hidden service online! Using the Tor Browser, if
you visit your hostname (the 16 characters followed by the .onion) you
should now see a page reading “Success: You Have Set Up Your Hidden
Service With NGINX”. You can now upload your files in the
/var/www/hidden_service/ directory or follow other setup guides on the
net to install other applications!
A blog about the use of educational technology in language learning and teaching
Monday, December 5, 2016
Wednesday, November 16, 2016
Backup and Restore PostgreSQL Databases
How to Back Up a PostgreSQL Database Using pg_dump
PostgreSQL includes a utility called "pg_dump" that can be used to dump database information into a file for backup purposes.The pg_dump utility is run from the Linux command line. The basic syntax of the command is:
pg_dump name_of_database > name_of_backup_fileThe command must be run by a user with privileges to read all of the database information, so it is run as the superuser most of the time.
For a real-world example, we can log into the "postgres" user and execute the command on the default database, also called "postgres":
sudo su - postgres pg_dump postgres > postgres_db.bakThis command is actually a PostgreSQL client program, so it can be run from a remote system as long as that system has access to the database.
If you wish to backup a remote system, you can pass the "-h" flag for specifying the remote host, and the "-p" flag to give the remote port:
pg_dump -h remote_host -p remote_port name_of_database > name_of_backup_fileYou can also specify a different user using the "-U" option if necessary. The syntax would be:
pg_dump -U user_name -h remote_host -p remote_port name_of_database > name_of_backup_fileKeep in mind that the same authentication requirements exist for pg_dump as for any other client program. This means that you must ensure that your log in credentials are valid for the systems you are trying to back up.
How to Restore Data Dumps from pg_dump with PostgreSQL
To restore a backup created by pg_dump, you can redirect the file into psql standard input:psql empty_database < backup_fileNote: this redirection operation does not create the database in question. This must be done in a separate step prior to running the command.
For example, we can create a new database called "restored_database" and then redirect a dump called "database.bak" by issuing these commands:
createdb -T template0 restored_database psql restored_database < database.bakThe empty database should be created using "template0" as the base.
Another step that must be performed in order to restore correctly is to recreate any users who own or have grant permissions on objects within the database.
For instance, if your database had a table owned by the user "test_user", you will have to create it on the restoration system prior to importing:
createuser test_user psql restored_database < database.bak
Dealing with Restoration Errors
By default, PostgreSQL will attempt to continue restoring a database, even when it encounters an error along the way.In many cases, this is undesirable for obvious reasons. It can be painful to try to sort out what operations are needed to restore the database to its proper state.
We can tell PostgreSQL to stop on any error by typing:
psql --set ON_ERROR_STOP=on restored_database < backup_fileThis will cause a PostgreSQL restore operation to halt immediately when an error is encountered.
This will still leave you with a crippled database that hasn't been fully restored, but you can now handle errors as they come up instead of dealing with a list of errors at the end.
A better option in many situations can be the "-1" (the number one) or "--single-transaction" option:
psql -1 restored_database < backup_fileThis option performs all of the restoration details in a single transaction.
The difference between this option and the "ON_ERROR_STOP" setting is that this will either succeed completely or not import anything.
This can be a costly trade-off for larger restorations, but in many cases, the benefit of not leaving you with a partially restored database heavily outweighs that cost.
How to Backup & Restore All Databases in PostgreSQL
To save time, if you would like to backup all of the databases in your system, there is a utility called "pg_dumpall".They syntax of the command is very similar to the regular pg_dump command, but it does not specify the database. Instead, the command backs up every available database:
pg_dumpall > backup_file
You can restore the databases by passing the file to psql, with the default database:psql -f backup_file postgres
Conclusion
Backups are an essential component in any kind of data storage plan. Fortunately, PostgreSQL gives you the utilities necessary to effectively backup your important information.As with any kind of backup, it is important to test your backups regularly to ensure the copies that are created can be restored correctly. The backups you create are only useful if they can actually be used to recover your system.
SOURCE By Justin Ellingwood
Monday, September 5, 2016
When To Use Abstract Class and Interface In Real Projects
Introduction
This is now an important question asked by an interviewer in the interview. I have found many solutions on the Internet regarding "When to use interface and abstract method?". Lately, I thought about writing an article on simplifying my experience and what I learned. If you check both the things, they seem to be very similar, which makes a confusion in the mind while answering these questions.
Here, in this article, I will try to explain these things.
Abstract Class
Before giving the introduction about abstract class, I will try to explain the abstract method, first.
Abstract Method
A method without any particular body is known as an abstract method. These methods contain only declaration of the method.To declare an abstract method, we have to use abstract modifier on the method.The class, under which these abstract methods are defined, is referred to as an abstract class, and this also has to be declared using abstract modifier.The implementation of abstract method is done by a derived class. When the abstract class inherits the derived class, the derived class must implement the abstract methods using override keyword in it.
This is now an important question asked by an interviewer in the interview. I have found many solutions on the Internet regarding "When to use interface and abstract method?". Lately, I thought about writing an article on simplifying my experience and what I learned. If you check both the things, they seem to be very similar, which makes a confusion in the mind while answering these questions.
Here, in this article, I will try to explain these things.
Abstract Class
Before giving the introduction about abstract class, I will try to explain the abstract method, first.
Abstract Method
A method without any particular body is known as an abstract method. These methods contain only declaration of the method.To declare an abstract method, we have to use abstract modifier on the method.The class, under which these abstract methods are defined, is referred to as an abstract class, and this also has to be declared using abstract modifier.The implementation of abstract method is done by a derived class. When the abstract class inherits the derived class, the derived class must implement the abstract methods using override keyword in it.
Abstract Class An abstract class is a special class that contains both abstract and non-abstract members in it.
Example
public abstract class Cars
{
//Abstract Methods
public abstract double price();
public abstract int getTotalSeat();
}
Here are some points regarding abstract class.
- Abstract class can contain abstract members as well as non-abstract members in it.
- A class can only inherit from one abstract Class.
- We cannot create object of an abstract class.
It is also user defined type like a class which only contains abstract members in it. These abstract members should be given the implementation under a child class of an interface. A class can be inherited from a class or from an interface.
Points to remember
- Interface contains only abstract methods.
- We cannot create object of an interface.
- The default scope for a member in Interface is Public. So, no need to use the Public access specifier in the program.
From both the definitions, it gets concluded that,
Figure 1
Figure 2
Now, I have class like Hyundai and Toyota which are derived from a parent class called Car. Here, I have the car methods as follow:
public class CarsHere, I have 2 types of cars which are inherited from Cars.
{
public string Wheel()
{
return "4 wheeler";
}
public string CheckAC()
{
return "AC is available";
}
public string CallFacility()
{
return "Call Facility supported";
}
}
using oops1;Now, it runs as expected and gives the following output .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace oops1
{
public class Hyundai : Cars
{
static void Main(string[] args)
{
Hyundai dust = new Hyundai();
Console.WriteLine(dust.CallFacility());
Console.WriteLine(dust.Wheel());
Console.WriteLine(dust.CheckAC());
Console.ReadLine();
}
}
}
Similarly, as Toyota is a car and it also inherits from Cars class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace oops1
{
public class Toyota : Cars
{
public string DiscountPrice()
{
return "20% discount on buying Toyoya Cars";
}
static void Main(string[] args)
{
Toyota Toy = new Toyota();
Console.WriteLine(Toy.CallFacility());
Console.WriteLine(Toy.Wheel());
Console.WriteLine(Toy.CheckAC());
Console.WriteLine(Toy.DiscountPrice());
Console.ReadLine();
}
}
}
We need some methods which are common to both the classes but their implementation is different.
- PRICE()- Both have price but different price.
- TotalSeat()- Both have total seats but different no. of seats.
- colors()- Both cars are of different colour.
So, here are the options for implementing these methods in both classes.
- Can I go for a normal class?
- Should I use interface here?
- Can I use an abstract class?
- If
we are taking class, then we can only write normal methods having
common implementation there. But, this will not satisfy our requirement
because we need separate implementations in both the classes. Thus, we
will not go forward with Class.
interface IExtraNow, let me first inherit the Toyota class from Cars class and IExtra interface class to achieve our goal.
{
double price();
int getTotalSeat();
string colors();
}
The code is given below.
namespace oops1
{
public class Toyota : Cars,IExtra
{
public string DiscountPrice()
{
return "20% discount on buying Toyoya Cars";
}
public double price()
{
return 1000000.00;
}
public int getTotalSeat()
{
return 5;
}
public string colors()
{
return "Red";
}
static void Main(string[] args)
{
Toyota Toy = new Toyota();
Console.WriteLine(Toy.CallFacility());
Console.WriteLine(Toy.Wheel());
Console.WriteLine(Toy.CheckAC());
Console.WriteLine(Toy.DiscountPrice());
Console.WriteLine("Total ONRoad Price:"+ Toy.price());
Console.WriteLine(Toy.getTotalSeat());
Console.WriteLine(Toy.colors());
Console.ReadLine();
}
}
So, the sketch diagram of this implementation will be like this.
Abstract Class
Now, we will see here how we can solve our problem using Abstract Class.
1. Define an abstract class as Car.
2. Put all the common functionality in simple methods and all the methods whose implementation is different but name is same. Make them Abstract method.
Here is my Car abstract class.
using System;Now, here is my Toyota class which is derived from Cars abstract class.
using System.Collections;
using System.Collections.Generic;
namespace oops1
{
public abstract class Cars
{
//put all the common functions but diffrent implementation in abstract method.
public abstract double price();
public abstract int getTotalSeat();
public abstract string colors();
//put all the common property in normal class
public string Wheel()
{
return "4 wheeler";
}
public string CheckAC()
{
return "AC is available";
}
public string CallFacility()
{
return "Call Facility supported";
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace oops1
{
public class Toyota : Cars
{
public string DiscountPrice()
{
return "20% discount on buying Toyoya Cars";
}
public override double price()
{
return 1000000.00;
}
public override int getTotalSeat()
{
return 5;
}
public override string colors()
{
return "Red";
}
static void Main(string[] args)
{
Toyota Toy = new Toyota();
Console.WriteLine("-------Common property defined commonly in Cars Class----------");
Console.WriteLine(Toy.CallFacility());
Console.WriteLine(Toy.Wheel());
Console.WriteLine(Toy.CheckAC());
Console.WriteLine("-------Own property defined in Toyota class------------");
Console.WriteLine(Toy.DiscountPrice());
Console.WriteLine("-------Common method but implementation is diffrent defined in IExtra Interface------------");
Console.WriteLine("Total ONRoad Price:"+ Toy.price());
Console.WriteLine(Toy.getTotalSeat());
Console.WriteLine(Toy.colors());
Console.ReadLine();
}
}
}
And thus, the result will be the same.
Conclusion
When we have the requirement of a class that contains some common properties or methods with some common properties whose implementation is different for different classes, in that situation, it's better to use Abstract Class then Interface.
Abstract classes provide you the flexibility to have certain concrete methods and some other methods that the derived classes should implement. On the other hand, if you use interfaces, you would need to implement all the methods in the class that extends the interface. An abstract class is a good choice if you have plans for future expansion.
Conclusion
When we have the requirement of a class that contains some common properties or methods with some common properties whose implementation is different for different classes, in that situation, it's better to use Abstract Class then Interface.
Abstract classes provide you the flexibility to have certain concrete methods and some other methods that the derived classes should implement. On the other hand, if you use interfaces, you would need to implement all the methods in the class that extends the interface. An abstract class is a good choice if you have plans for future expansion.
Now, I will explain the second use of Abstract Class here.
Imagine,
we have taken a normal parent class as Cars where we have only defined
the common methods. And, my Toyota class is derived from the Cars class.
This will look like the below code.
public class CarsAnd, here is the Toyota class after inheriting from Cars.
{
public string Wheel()
{
return "4 wheeler";
}
public string CheckAC()
{
return "AC is available";
}
public string CallFacility()
{
return "Call Facility supported";
}
}
using System;Here, users know only the Toyota class, its methods, and properties. The user can access the Cars class property and method by creating the object of Toyota class because it is a child class.
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace oops1
{
public class Toyota : Cars
{
public string DiscountPrice()
{
return "20% discount on buying Toyoya Cars";
}
static void Main(string[] args)
{
Console.ReadLine();
}
}
}
Now, the main demerit of this kind of Implementation is that it allows the user to create the object of the Parent class (which the user should not be aware of and this is not his strategy). Let's see what happens when the user creates the object.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace oops1
{
public class Toyota : Cars
{
public string DiscountPrice()
{
return "20% discount on buying Toyoya Cars";
}
static void Main(string[] args)
{
//Toyota Toy = new Toyota();
Cars ca = new Cars();
Console.WriteLine("-------Common property defined commonly in Cars Class----------");
Console.WriteLine(ca.CallFacility());
Console.WriteLine(ca.Wheel());
Console.WriteLine(ca.CheckAC());
Console.WriteLine("-------Own property defined in Toyota class------------");
Console.WriteLine(ca.DiscountPrice());
Console.ReadLine();
}
}
}
As we know, we won't be able to access the child class methods using parent class object, this Cars object will not access the DiscountPrice() Method because
it is a child class method. This implementation will not satisfy our
requirement. So, even if the user will create an object of Parent class,
we need to check them because using that object, he can't able to
access the child class method.
So, the main problem we face here is,
As the user is unaware of parent class, he is able to create the object of parent class and unable to access the child class method using parent class. So, to restrict this, we have to do the following things-
- We should not give the permission to create the object of parent class in child class
- We can only allow the user to create the child class object to access both parent class methods and child class methods.
Simple to do this Create the base class as an Abstract class and that will solve our problems as follow.
using System;
using System.Collections;
using System.Collections.Generic;
namespace oops1
{
public abstract class Cars
{
public string Wheel()
{
return "4 wheeler";
}
public string CheckAC()
{
return "AC is available";
}
public string CallFacility()
{
return "Call Facility supported";
}
}
}
- Even if you want to create the object of parent class, it shows the following error.
So, this will solve our problem.
Conclusion
So, in those cases, we will use abstract class where we want to restrict the user from creating the object of parent class because by creating object of parent class, you can't call child class methods. So, the developer has to restrict accidental creation of parent class object by defining it as abstract class.
So, I think, in these ways, we can use abstract class in our real time project.
When To Use Interface In Real Time Project?
INTERFACE
It is also user-defined type like a class which only contains abstract members in it and these abstract members should be given implementation under a child class of an interface. A class can inherit from a class or from an interface.
It is also user-defined type like a class which only contains abstract members in it and these abstract members should be given implementation under a child class of an interface. A class can inherit from a class or from an interface.
interface I1
{
void MethodToImplement();
}
In your daily
programming, you are using a lot of interfaces knowingly or unknowingly.
If you are using a List, Dictionary, or Hash Table etc in your project,
then you are indirectly using interface in your project because all
collections are derived from an Interface, IEnumerable.
Here, I will not discuss about the uses of Interface. I will discuss when can we use our interface in C#.
Before explaining in details, I will ask you to focus on the following points.
Here, I will not discuss about the uses of Interface. I will discuss when can we use our interface in C#.
Before explaining in details, I will ask you to focus on the following points.
- In C++, we have a concept of Multiple Inheritance where we find a serious problem called Diamond Problem.
- Thus, in C#, multiple inheritance is not supported. When there is a situation like multiple inheritance, use Interface.
The solution of the multiple inheritance can be provided by Interface. So, we can do this example using Interface as follows. In this way, the diamond problem of Inheritance is solved.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OOPs2
{
interface Demo1
{
void print();
}
interface Demo2
{
void print();
}
class Program:Demo1,Demo2
{
void Demo1.print()
{
Console.WriteLine("Debendra");
}
void Demo2.print()
{
Console.WriteLine("Debendra");
}
static void Main(string[] args)
{
Program p = new Program();
((Demo2)p).print();
Console.ReadLine();
}
}
}
using System;Now, here is my Toyota class which is derived from Cars.
using System.Collections;
using System.Collections.Generic;
namespace oops1
{
public class Cars
{
public string Wheel()
{
return "4 wheeler";
}
public string CheckAC()
{
return "AC is available";
}
public string CallFacility()
{
return "Call Facility supported";
}
}
}
using System;Here is my Hyundai class which is derived from Cars.
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace oops1
{
public class Toyota : Cars
{
static void Main(string[] args)
{
Toyota Toy = new Toyota();
Console.WriteLine(Toy.CallFacility());
Console.WriteLine(Toy.Wheel());
Console.WriteLine(Toy.CheckAC());
Console.ReadLine();
}
}
}
using oops1;A new feature for the Hyundai car is Introduced called GPS which is not supported in Toyota cars. Then, how can we implement and which way we can implement these?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace oops1
{
public class Hyundai:Cars
{
static void Main(string[] args)
{
Hyundai dust = new Hyundai();
Console.WriteLine(dust.CallFacility());
Console.WriteLine(dust.Wheel());
Console.WriteLine(dust.CheckAC());
Console.ReadLine();
}
}
}
Here, we have certain options like
- Go for a new class defining the GPS method and inherit it to the Hyundai Class.
- Go for an abstract class and define GPS method and inherit it on Hyundai class and implement the GPS method there.
- Directly create a method in Hyundai class and consume it.
- Go for Interface
.
CASE 1 - By Using simple class
Let's find what will happen if we use a class there, and declare a method as GPS and try to inherit in Hyundai class.
Created a new class as "NewFeatures, as shown below.
class NewFeaturesNow, inherit the Hyundai class from NewFeatures. So, if we check this class, it was previously inherited from Cars class and for now, again inherits from NefFeatures class. So, it gives the following error when you try to run the program.
{
public void GPS()
{
Console.WriteLine("GPS supported");
}
}
using oops1;Now, run the program and find out the error.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace oops1
{
public class Hyundai:Cars,NewFeatures
{
static void Main(string[] args)
{
Hyundai hun = new Hyundai();
Console.WriteLine(hun.CallFacility());
Console.WriteLine(hun.Wheel());
Console.WriteLine(hun.CheckAC());
Console.ReadLine();
}
}
}
This is simple because C# does not support multiple inheritance.
CASE 2 - By using Abstract class
Now, go for abstract class and see what happens.
public abstract class NewFeaturesNow, let's try to inherit from abstract class.
{
abstract public void GPS();
}
using oops1;So, here is the error I got.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace oops1
{
public class Hyundai:Cars,NewFeatures
{
public override void GPS()
{
Console.WriteLine("GPS supported.");
}
static void Main(string[] args)
{
Hyundai hun = new Hyundai();
Console.WriteLine(hun.CallFacility());
Console.WriteLine(hun.Wheel());
Console.WriteLine(hun.CheckAC());
Console.ReadLine();
}
}
}
CASE 3 - Direct creating a method called GPS() inside Hyundai class
This is very relevant way to use a unique method but it has a small problem. If for any reason we forget to create such common method, then it will not ask to write methods.Today, we are using one unique method so that is OK we can remember and write the method. Suppose, we have hundreds of such common methods and we forget to write 2 of them then it will run but not give the expected output,so we have to skip the way and go for the fourth one by defining interface.
CASE 4 - By defining Interface
This is the most important case and we will see how it will solve our problem.Lets define the method in an Interface
interface INewFeaturesNow inherit the Interface from Cars and see without implementing the GPS() method.
{
void GPS();
}
using oops1;As we have not implemented the method it will show the following error as follow.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace oops1
{
public class Hyundai:Cars, INewFeatures
{
static void Main(string[] args)
{
Hyundai hun = new Hyundai();
Console.WriteLine(hun.CallFacility());
Console.WriteLine(hun.Wheel());
Console.WriteLine(hun.CheckAC());
Console.ReadLine();
}
}
}
So, the problems which happen in case 3 can be easily solved by using Interface. Now, let's implement the method and see will it solve the problem which arises in Case1 and case2 as follows.
using oops1;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace oops1
{
public class Hyundai:Cars,INewFeatures
{
public void GPS()
{
Console.WriteLine("GPS supported.");
}
static void Main(string[] args)
{
Hyundai hun = new Hyundai();
Console.WriteLine(hun.CallFacility());
Console.WriteLine(hun.Wheel());
Console.WriteLine(hun.CheckAC());
hun.GPS();
Console.ReadLine();
}
}
}
Thus, it resolves the demerits of all the above 3 cases. So, in this situation, we have to use Interface. Here, I have shown you the sketch diagram.
In this way, we can use abstract class and interface in our project depending on the condition.
Hope this article gives you an idea about when to use these 2 important things.If you have any suggestions, please feel free to comment so that I can include that in this article.
SOURCE: http://www.c-sharpcorner.com/article/when-to-use-abstract-class-and-interface-in-real-time-projects/
Subscribe to:
Posts (Atom)