Reputation: 145
I'm a very green thumb to Java and would like to know how to properly use an interface to connect classes.
Say there is an interface X, in package Y for the volume and area of a shape
package Y;
public interface Shape {
public double volume();
public double surfaceArea();
}
Given a class called tetrahedron, where the math for the volume and area are respectively
package Y;
public class Tetrahedron implements Shape{
Tetrahedron(double edge) {
(volume) Math.pow(edge, 3)/(6*Math.sqrt(2));
(area) Math.sqrt(3)*Math.pow(edge, 2);
}
}
Which is then once again accessed by the main class, also in package Y
package Y;
public class Main {
static void main(String[] args){
Shape a = new Tetrahedron(5);
System.out.println(a.volume());
System.out.println(a.surfaceArea());
}
}
How exactly would you go about connecting the interface to the second class?
As far as I am aware, you cannot simply override the value of volume
and surfaceArea
by doing something such as volume = x
, so how exactly does one use the interface to get from A to B to C?
Upvotes: 0
Views: 1777
Reputation: 187
I think you should do like this.
public interface Shape {
public double volume();
public double surfaceArea();
}
public class Tetrahedron implements Shape{
double edge;
Tetrahedron(double edge) {
this.edge=edge;
}
@Override
public double volume(){
return Math.pow(edge, 3)/(6*Math.sqrt(2));
}
@Override
public double surfaceArea(){
return Math.sqrt(3)*Math.pow(edge, 2);
}
}
Upvotes: 1