Java Beginners

Moderators: zibadian
Number of threads: 1285
Number of posts: 2739

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
Interfaces and some unknown declaration (I am completely lost) Posted by Kericr on 4 Aug 2007 at 1:36 PM
Question 1: I'm still very very new to Java and in the course of my self-study I've started to look at interfaces. I think I understand the concept of an interface, but I'm having trouble determining why someone would use it. I'm going through the Sam's "learn Java in 21 days" book and using the resourses available on Sun's site explaining interfaces to try to figure this out, but I'm still lost. Below is a sample program from Sun's learning Java tutorial located on their website.

Original Link: http://java.sun.com/docs/books/tutorial/java/IandI/usinginterface.html

First, an interface class file has been created:

public interface Relatable {
public int isLargerThan(Relatable other);
}

Then a class is created to implement the interface:

import java.awt.Point;

public class RectanglePlus implements Relatable {
public int width = 0;
public int height = 0;
public Point origin;

// four constructors
public RectanglePlus() {
origin = new Point(0, 0);
}
public RectanglePlus(Point p) {
origin = p;
}
public RectanglePlus(int w, int h) {
origin = new Point(0, 0);
width = w;
height = h;
}
public RectanglePlus(Point p, int w, int h) {
origin = p;
width = w;
height = h;
}

// a method for moving the rectangle
public void move(int x, int y) {
origin.x = x;
origin.y = y;
}

// a method for computing the area of the rectangle
public int getArea() {
return width * height;
}

// a method to implement Relatable
public int isLargerThan(Relatable other) {
RectanglePlus otherRect = (RectanglePlus)other;
if (this.getArea() < otherRect.getArea())
return -1;
else if (this.getArea() > otherRect.getArea())
return 1;
else
return 0;
}
}

From here, I created my own class file to test (and try to understand) the concept:

class RectComp {
public static void main(String[] Args) {
int rect1 = 5;
int rect2 = 4;
RectanglePlus test = new RectanglePlus(rect1, rect1);
RectanglePlus test2 = new RectanglePlus(rect2, rect2);

System.out.println(test.isLargerThan(test2));

}
}

This program works as expected and for the values provided, returns 1. The problem I run into is when I make the following changes to the 'RectanglePlus' file:

import java.awt.Point;

// This is a demonstration of the concept of implementation

// public class RectanglePlus implements Relatable {

// Test change to determine if this can be done w/o an interface
public class RectanglePlus {

// Class variables

public int width = 0;
public int height = 0;
public Point orgin;

// Four constructor methods, based on agruments provided

public RectanglePlus() {
orgin = new Point(0, 0);
}

public RectanglePlus(Point p) {
orgin = p;
}

public RectanglePlus(int w, int h) {
orgin = new Point(0, 0);
width = w;
height = h;
}

public RectanglePlus(Point p, int w, int h) {
orgin = p;
width = w;
height = h;
}

// A class method used to move the orgin point
public void move(int x, int y) {
orgin.x = x;
orgin.y = y;
}

// A class method used to determine the area of a rectangle
public int getArea() {
return width * height;
}

// a method to implement Relatable (?)

public int isLargerThan(RectanglePlus other) {
RectanglePlus otherRect = (RectanglePlus)other;
if (this.getArea() < otherRect.getArea())
return -1;
else if (this.getArea() > otherRect.getArea())
return 1;
else
return 0;
}
}

When using this file, the program works the same exact way and doesn't implement anything. I don't see the purpose of the interface. Can someone help me understand this concept better by explaining to me why I would want to implement an interface as opposed to simply writing the class itself as an argument?

Question 2: Using the same program above, specifically one line:

RectanglePlus otherRect = (RectanglePlus)other;

I don't know what this means, I don't know how it works. My book used it too (in a slightly different context, using

int z =(int)(x/y);

I understand it's declaring a variable z, but I don't know what z ends up being.

I appriciate any and all help someone can provide me with these problems.
Report
Re: Interfaces and some unknown declaration (I am completely lost) Posted by IDK on 4 Aug 2007 at 2:49 PM
An interface is simply a way of interfacing a class...

This is a classic example (which I've simplified and changed and shortened a little):

Say you have a mammals class and a bird class.
You implement a way of making birds fly.
Now all you have to do is to use inherence to make new bird and mammals spicies.

Then you come up with a bat spicies.
It can fly, and could thus be categoriced as a bird, but it's in fact a mammal, and had has all the caracteristiscts of mammals. Then you make it inherit from mammals. In C++ you would inherit from birds to (this is called multiple inherence, which is removed in Java), which can give devastating problems. For example, now maybe the bat can lay eggs.

The best solution is to use interfaces. If you create a fly interface, then you use that in the bat class. Now everything works as expected.

To generalize, if you have something that you can do with two different classes, but not their parents, then you should use interfaces.

Happy coding wishes
the one and only
Niklas Ulvinge aka IDK
Report
Re: Interfaces and some unknown declaration (I am completely lost) Posted by zibadian on 4 Aug 2007 at 3:05 PM
First the answer to your last question: Type-casting
The type specified between the brackets in front of some variable changes that variable into that type. For example:
  double x = 1;
  double y = 2;
  int z = x/y; // compiler error

This code will not compile, because x/y is not an integer but a double. This makes the assignment to z illegal. By specifically stating that the compiler should treat x/y as an integer (i.e. type-casting), you "add" code to change the value of x/y into an integer:
  int z = (int) x/y; // x/y is first calculated as double, then changed into an integer

This becomes even more important when dealing with objects. Type-casting allows objects to be stored in a list and still maintain all their functionality; or be passed as a parameter to a general method. Here's an example of a method to add 1 to any object:
  public Object addOne(Object o) {
    if (o instanceof Integer) {
      return new Integer( ((Integer) o)+1);
    } else if (o instanceof String) {
      return new String(""+Integer.parseInt((String) o)+1);
    } else if (o instanceof Double) {
      return new Double( ((Double) o)+1);
    } else
      return null;
  }

This way you only need to write 1 method to handle all the cases, instead of 1 method for each object type.
Report
Re: Interfaces and some unknown declaration (I am completely lost) Posted by Kericr on 6 Aug 2007 at 1:58 PM
: An interface is simply a way of interfacing a class...
:
: This is a classic example (which I've simplified and changed and
: shortened a little):
:
: Say you have a mammals class and a bird class.
: You implement a way of making birds fly.
: Now all you have to do is to use inherence to make new bird and
: mammals spicies.
:
: Then you come up with a bat spicies.
: It can fly, and could thus be categoriced as a bird, but it's in
: fact a mammal, and had has all the caracteristiscts of mammals. Then
: you make it inherit from mammals. In C++ you would inherit from
: birds to (this is called multiple inherence, which is removed in
: Java), which can give devastating problems. For example, now maybe
: the bat can lay eggs.
:
: The best solution is to use interfaces. If you create a fly
: interface, then you use that in the bat class. Now everything works
: as expected.
:
: To generalize, if you have something that you can do with two
: different classes, but not their parents, then you should use
: interfaces.
:
: Happy coding wishes
: the one and only
: Niklas Ulvinge aka IDK

Thank you very much for your response, but I'm still a little confused. I can somewhat see the application of an interface here, but using your example, couldn't I just make a flight method inside the bat subclass? I mean the interface doesn't contain any code, it's just a declaration and arguments, right? I still have to write out how the method works. Perhaps I'm still a little too green to understand this? Could you perhaps provide more clarification?

Report
Re: Interfaces and some unknown declaration (I am completely lost) Posted by IDK on 6 Aug 2007 at 2:47 PM
: : An interface is simply a way of interfacing a class...
: :
: : This is a classic example (which I've simplified and changed and
: : shortened a little):
: :
: : Say you have a mammals class and a bird class.
: : You implement a way of making birds fly.
: : Now all you have to do is to use inherence to make new bird and
: : mammals spicies.
: :
: : Then you come up with a bat spicies.
: : It can fly, and could thus be categoriced as a bird, but it's in
: : fact a mammal, and had has all the caracteristiscts of mammals. Then
: : you make it inherit from mammals. In C++ you would inherit from
: : birds to (this is called multiple inherence, which is removed in
: : Java), which can give devastating problems. For example, now maybe
: : the bat can lay eggs.
: :
: : The best solution is to use interfaces. If you create a fly
: : interface, then you use that in the bat class. Now everything works
: : as expected.
: :
: : To generalize, if you have something that you can do with two
: : different classes, but not their parents, then you should use
: : interfaces.
: :
: : Happy coding wishes
: : the one and only
: : Niklas Ulvinge aka IDK
:
: Thank you very much for your response, but I'm still a little
: confused. I can somewhat see the application of an interface here,
: but using your example, couldn't I just make a flight method inside
: the bat subclass? I mean the interface doesn't contain any code,
: it's just a declaration and arguments, right? I still have to write
: out how the method works. Perhaps I'm still a little too green to
: understand this? Could you perhaps provide more clarification?
:
:

But what if you want to use the classes. For example if you wan't to tell an animal to fly if it can fly you can do like this with intefcases (in psuedo code):
if animal can fly
  fly!


Without interfaces, you would need to do like this:
if animal inherits from bird, or animal is a bat, ...
  fly!


Which is much less dynamic.
Report
Re: Interfaces and some unknown declaration (I am completely lost) Posted by zibadian on 6 Aug 2007 at 8:05 PM
: : : An interface is simply a way of interfacing a class...
: : :
: : : This is a classic example (which I've simplified and changed and
: : : shortened a little):
: : :
: : : Say you have a mammals class and a bird class.
: : : You implement a way of making birds fly.
: : : Now all you have to do is to use inherence to make new bird and
: : : mammals spicies.
: : :
: : : Then you come up with a bat spicies.
: : : It can fly, and could thus be categoriced as a bird, but it's in
: : : fact a mammal, and had has all the caracteristiscts of mammals. Then
: : : you make it inherit from mammals. In C++ you would inherit from
: : : birds to (this is called multiple inherence, which is removed in
: : : Java), which can give devastating problems. For example, now maybe
: : : the bat can lay eggs.
: : :
: : : The best solution is to use interfaces. If you create a fly
: : : interface, then you use that in the bat class. Now everything works
: : : as expected.
: : :
: : : To generalize, if you have something that you can do with two
: : : different classes, but not their parents, then you should use
: : : interfaces.
: : :
: : : Happy coding wishes
: : : the one and only
: : : Niklas Ulvinge aka IDK
: :
: : Thank you very much for your response, but I'm still a little
: : confused. I can somewhat see the application of an interface here,
: : but using your example, couldn't I just make a flight method inside
: : the bat subclass? I mean the interface doesn't contain any code,
: : it's just a declaration and arguments, right? I still have to write
: : out how the method works. Perhaps I'm still a little too green to
: : understand this? Could you perhaps provide more clarification?
: :
: :
:
: But what if you want to use the classes. For example if you wan't to
: tell an animal to fly if it can fly you can do like this with
: intefcases (in psuedo code):
:
: 
: if animal can fly
:   fly!
: 
:
:
: Without interfaces, you would need to do like this:
:
: 
: if animal inherits from bird, or animal is a bat, ...
:   fly!
: 
:
:
: Which is much less dynamic.

Not only that, but what if some future fish starts to fly. Without interfaces, you'll need to update all the code, which depend on the fly() method.
With interfaces, then that fish can simply implement the Flight interface and no other code needs to be changed.
Interfaces are a way of telling the compiler that a certain class has certain methods, without telling the programmer of how to implement those methods.



 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.