how interface know which class method call? - c#-4.0

i have one doubt if if we have two classes with same method,object of class doesnt know which method to call this situtation we use interface? but how interface know which class method to call,how to apply interface ,i have some code plz check and tell me?
namespace IntExample
{
interface Iinterface
{
public void add();
public void sub();
}
public partial class Form1 : Form,Iinterface
{
public Form1()
{
InitializeComponent();
}
public void add()
{
int a, b, c;
a = Convert.ToInt32(txtnum1.Text);
b = Convert.ToInt32(txtnum2.Text);
c = a + b;
txtresult.Text = c.ToString();
}
public void sub()
{
int a, b, c;
a = Convert.ToInt32(txtnum1.Text);
b = Convert.ToInt32(txtnum2.Text);
c = a - b;
txtresult.Text = c.ToString();
}
private void btnadd_Click(object sender, EventArgs e)
{
add();
}
private void button2_Click(object sender, EventArgs e)
{
sub();
}
class cl2 : Form1,Iinterface
{
public void add()
{
int a, b, c;
a = Convert.ToInt32(txtnum1.Text);
b = Convert.ToInt32(txtnum2.Text);
c = a + b;
txtresult.Text = c.ToString();
}
}
}
}

An interface is an abstraction, one that allows you to perform polymorphism without the need for inheritance. As such, an "interface variable" holds an instance of a concrete class, and the current instance's class is always used for method lookups by the interface as long as the variable contains that instance.

Related

Real method getting executed inspite of mocking

I am new to Java unit testing and started using Mockito. I am using doNothing.... but the real method get always executed. Not sure what I am missing.
public abstract class MyApplication {
private Square s;
private Circle c;
public MyApplication(Square s, Circle c){
this.s = s;
this.c = c;
}
public void firstMethod() {
System.out.println("Starting first Method");
secondMethod();
System.out.println("Ending first Method");
}
public void secondMethod() {
//some business logic here
}
}
public class SmallApplication extends MyApplication {
private Square s;
private Circle c;
public SmallApplication(Square s, Circle c){
this.s = s;
this.c = c;
}
}
public class MyApplicationTest {
public void testFirstMethod() {
Square smock = mock(Square.class);
Circle cmock = mock(Circle.class);
SmallApplication app = new SmallApplication(smock, cmock);
SmallApplication appSpy = spy(app);
doNothing().when(appSpy).secondMethod();
appSpy.firstMethod();
}
}
I donot want seconMethod's business logic to be executed but with the above code the second method business logic is always executed. Please help out.

How can I call this method using a button?

public static bool WriteBeamDataToFile(string Filename, List<Part> Parts)
{
// Open a Streamwriter to write data to the specified Filename
using (StreamWriter TeklaDataWriter = new StreamWriter(Filename))
{
// Connect to the Currently Open Tekla Model
Model Model = new Model();
foreach (Part CurrentPart in Parts)
{
if (CurrentPart != null)
{
string Name = CurrentPart.Name;
string Profile = CurrentPart.Profile.ProfileString;
string Material = CurrentPart.Material.MaterialString;
string Finish = CurrentPart.Finish;
TeklaDataWriter.WriteLine(Name + "," + Profile + "," + Material + "," + Finish);
}
}
}
return File.Exists(Filename);
}
Example:
private void button1_Click(object sender, EventArgs e)
{
How to call above method here?
}
private void button1_Click(object sender, EventArgs e) {
private bool isFileExists;
List<Parts> partsList = new List<Parts>();
isFileExists = WriteBeamDataToFile("example.txt",partsList)
if(isFileExists){
//do something..
}
}
Method above is mark as static. That's why you faced some issue.
Static method could be call from Class it' self.
While non static methods could be called from class instance.
See example:
class MyClass {
//static method
public static void Method1() {}
//non static method
public void Method2() {}
}
class MyForm:Form {
...
private void button1_Click(object sender, EventArgs e)
{
//here we call static method of MyClass
MyClass.Method1();
}
//or
private void button1_Click(object sender, EventArgs e)
{
// Here we create an instance of MyClass
var class = new MyClass();
// and call non static Method
class.Method2();
}
}
}

Is there a way to find out which class instance created 'this'

**I(one instance of a class) want to find out say which class instantiated me?
I have a class C that is instantiated by Class A and Class B. I want to find out which class instantiated me, so that I can access the variable from that class.
The usual way is to pass in an identifier that hey I am from class A and pass in the variable x in the constructor for the C to consume in the way appropriate for it.
**
eg:
public Class A
{
public int x;
public A()
{
C c = new C();
}
}
public Class B
{
public int x;
public B()
{
C c = new C();
}
}
public Class C
{
public CMethod()
{
// I want Access int x from the class that instantiated me.
if I know its B then B.x ...
}
}
There is no way to know without some hacking (see below). This looks like a case for an interface…
Classes A and B define HasX which has a getX() method. You can pass either class to the constructor of C which expects any class which implements HasX. Then C can call getX on either object and it doesn't need to know which type it actually is, but it will get the appropriate X value.
public interface HasX {
public int getX();
}
public class A implements HasX {
private int x;
public A()
{
C c = new C(this);
}
public int getX() {
return x;
}
}
public class B implements HasX {
private int x;
public B() {
C c = new C(this);
}
public int getX() {
return x;
}
}
public class C {
HasX hasX;
public C(HasX hasX) {
this.hasX = hasX;
}
public void doStuff() {
int x = hasX.getX();
}
}
To answer you original question though, the object which created an object is not stored anywhere… but you can do some hacking when C is constructed for find out the class. Here is some code I once used for a Logging implementation which could detect who was the caller by looking back along the stracktrace of a Throwable. Again, this is not good practice, but you asked so… :)
From: https://github.com/slipperyseal/atomicobjects/blob/master/atomicobjects-lang/src/main/java/net/catchpole/trace/PrintTrace.java
public C() {
String whoCalledMe = whereAmI(new Throwable());
}
private String whereAmI(Throwable throwable) {
for (StackTraceElement ste : throwable.getStackTrace()) {
String className = ste.getClassName();
// search stack for first element not within this class
if (!className.equals(this.getClass().getName())) {
int dot = className.lastIndexOf('.');
if (dot != -1) {
className = className.substring(dot + 1);
}
return className + '.' + ste.getMethodName();
}
}
return "";
}
You might want to edit this to simply return the class name, or even do a Class.forName() to resolve the actual class.
If you want the actual objects, and there is only ever 1 of each class, you could out the objects in a Map keyed on classname. But gee what a mess around :)

proxy pattern no suitable methods found to override? Help i'm not sure what just went wrong

This is all in the form...
namespace Proxy_Pattern
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
double bankAmount = 1000.00;
private void btnCheck_Click(object sender, EventArgs e)
{
double amount;
amount = double.Parse(txtAmount.Text);
CheckProxy cp =new CheckProxy();
cp.CheckTransactionRequest(amount);
lbltotal.Text = bankAmount.ToString();
}
private void btnCreditCard_Click(object sender, EventArgs e)
{
}
}
abstract class BankSubject
{
public abstract void CreditTransactionRequest(double amount);
public abstract void CheckTransactionRequest(double amount);
}
class RealBankSubject : BankSubject
{
double bank;
public RealBankSubject(double m_bacc)
{
bank = m_bacc;
}
public override void CreditTransactionRequest(double num)
{
bank -= num;
}
public override void CheckTransactionRequest(double num)
{
bank += num;
}
}
Does not implement inherited abstract members.... but why?
class CreditCardProxy : BankSubject
{
RealBankSubject realSubject;
double amount;
public CreditCardProxy (double m_bacc)
{
amount = m_bacc ;
}
no suitable method to override?... how is this an error? I have a method right here?
public override void CreditTransactionRequest()
{
if (realSubject == null)
{
realSubject = new RealBankSubject(amount);
}
realSubject.CreditTransactionRequest(amount);
}
public override void CheckTransactionRequest()
{
}
}
class CheckProxy : BankSubject
{
RealBankSubject realSubject;
double amount;
public override void CreditTransactionRequest()
{
}
public override void CheckTransactionRequest()
{
if (realSubject == null)
{
realSubject = new RealBankSubject(amount);
}
realSubject.CheckTransactionRequest(amount);
}
}
}
In your proxy, you are not specifying the amount as a parameter to the method:
public override void CreditTransactionRequest();
So it cannot override
public abstract void CreditTransactionRequest(double amount);
as the method signature doesn't not match
CreditTransactionRequest in CreditCardProxy does not take any arguments but CreditTransactionRequest in BankSubject does. This is why you can not override the method the signatures do not match.

generic delete does not work?

I have this abstract repository class with a Delete method:
public abstract class MyRepository<C, T> :
IMyRepository<T>
where T : class
where C : ObjectContext, new()
{
private C _entities = new C();
public C Context
{
get { return _entities; }
set { _entities = value; }
}
public virtual void Delete(T entity)
{
_entities.Attach(entity);
_entities.DeleteObject(entity);
_entities.SaveChanges();
}
}
however this does not compile? how can I Create a generic delete method here?
Instead of this
private C _entities = new C();
Use Activator.CreateInstance:
private C _entities = Activator.CreateInstance<T>();
Modify your Delete method as follows
public virtual void Delete(T entity)
{
_entities.CreateObjectSet<T>().Attach(entity);
_entities.DeleteObject(entity);
_entities.SaveChanges();
}
public virtual void Update(T entity)
{
_entities.CreateObjectSet<T>().Attach(entity);
_entities.ObjectStateManager
.ChangeObjectState(entity, System.Data.EntityState.Modified);
_entities.SaveChanges();
}

Resources