Joining method from another class in java -
i'm trying understand java trying several things out. i'm using 2 classes in same package. 1 called box
, other 1 called testbox
. want calculate area of company box using calculatearea()
. function in class testbox
. function calculatearea
in box
not respond function in testbox
. i'm missing link between these 2 classes. seems simple problem, have not found solution yet. can please me out?
package box; public class box { int length; int width; public static void main(string[] args) { box company = new box(); company.length = 3; company.width = 4; int area = company.calculatearea(); } }
package box; public class testbox { int length; int width; int calculatearea(){ int area = length * width; system.out.println("area= " + area); return area; } }
i think have clarify bit design, mean classes box , testbox should do, advice use use ide such eclipse or intellij idea helping syntax highlight , founding possible errors.
what dealing encapsulation,
packing of data , functions single component.
so feasible area of box calculated box class itself.
about code, possible solution be:
package com.foo; public class main { public static void main(string[] args) { box box = new box(3, 4); int area = box.calculatearea(); system.out.println("box area is: " + area); } } class box { private int l; private int w; box(int length, int width) { l = length; w = width; } int calculatearea() { return l * w; } }
another possible approach be
package com.foo; public class main { public static void main(string[] args) { box box = new box(3, 4); testbox testbox = new testbox(); int area = testbox.calculatearea(box); system.out.println("box area is: " + area); } } class box { private int l; private int w; box(int length, int width) { l = length; w = width; } public int getlength() { return l; } public int getwidth() { return w; } } class testbox { int calculatearea(box box) { return box.getlength() * box.getwidth(); }
if want have separate class doing job, not like, function computing area related box , works on box variables, prefer first one, should better have more details in case.
i hope helps.
Comments
Post a Comment