Log in

View Full Version : Overriding Methods in Java


VerizoniPhone
March 26th, 2013, 07:13 PM
I would like help with his problem. I cant find anything on this topic. (maybe I'm searching the wrong thing)

Im very confused any help would be awesome

Define a subclass of C named B that overrides method m1() so that it returns the difference between m and n.

public class C
{
private int m;
private int n;

public C(int mIn, int nIn)
{
m = mIn;
n = nIn;
}
public int m1()
{
return m+n;
}
}

ethanf93
March 26th, 2013, 09:22 PM
It's not really clear from your question what you've tried and what you've been taught but you might try: http://docs.oracle.com/javase/tutorial/java/IandI/override.html

Lots of that page will probably be over your head but reading the code examples should point you in the right direction.

TheMatrix
March 27th, 2013, 01:13 AM
Typically you have something like this:

public class BaseClassA {
//make member variables "protected" so that base classes can get them without the need for accessors
protected int m_m; //FYI: the m_ is actually a C++ thing, in some coding standards
protected int m_n;

public BaseClassA(int m, int n);
this.m_m = m;
this.m_n = n;
}

public int m1() {
return this.m_m; //The base class might do something else than what you want
}
}

public class SubClassB extends BaseClassA { //notice the "extends" bit -- that's how you carry over
@Override //this is what it's all about
public int m1() {
return this.m_m - this.m_n; //see, in this version, you do something else with everything else being the same
}
}

//later...
public class MyApp {
public static void main(String[] argv) {
SubClassB thing = new SubClassB(7, 9);
System.out.writeln(thing.m1());
}
}

(Question to other Java programmers: do you need the constructor in SubClassB? I haven't used Java for a while, please correct me if I'm wrong)

HTH