Joining method from another class in java - java

I'm trying to understand Java by trying several things out. I'm using two classes in the same package. One is called Box, the other one is called TestBox. I want to calculate the area of the company box using calculateArea(). This function is in another class TestBox. However the function calculateArea in Box does not respond to the function in TestBox. I'm missing a link between these two classes. This seems like a simple problem, but I have not found the solution yet. Can someone please help 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 you have to clarify a bit what is your design, I mean what the classes Box and TestBox should do, moreover I advice use to use an IDE such as Eclipse or Intellij Idea helping you with syntax highlight and founding possible errors.
What you are dealing with is the encapsulation, that is
packing of data and functions into a single component.
so it is feasible that the area of the box is calculated by the Box class itself.
About your code, a possible solution could 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 could 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 you want to have a separate class doing the job, but it is something I do not like, the function computing the area is related to the box and works on box variables, I prefer the first one, but it should be better to have more details in case.
I hope it helps.

As per the below approach, you need to make parameterized constructor where you can pass the value of length and width at the time of creating TestBox object. You also need to create a default constructor for future save in case if later you only want to create default TestBox object like new TestBox();
You can calculate area in you TestBox class and than return the value in the Box class. You don't need to create separate length and width variable in Box class and no need to create a object of Box.
package box;
public class Box {
public static void main(String[] args) {
TestBox company = new TestBox (3,4);
int area = company.calculateArea();
}
}
package box;
public class TestBox {
private int length;
private int width;
TestBox()
{
}
TestBox(int l, int w)
{
this.length = l;
this.width = w;
}
public int getLength() {
return length;
}
public int getWidth() {
return width;
}
int calculateArea(){
int area = length * width;
System.out.println("Area= " + area);
return area;
}
}

public static void main(String[] args) {
TestBox company = new TestBox();
company.length = 3;
company.width = 4;
int area = company.calculateArea();
}
}

Related

Can variables be used to create object in Java?

How do I do something like this? I want to take command line arguments like Circle 10 or Rectangle 20 30 and create objects of the corresponding classes.
class Circle{
//Some lines here
}
class Rectangle{
//Some lines here
}
public class Perimeter{
public static void main(String[] args) {
for(int i=0; i< args.length; i++){
String shape = args[0];
shape curr_shape = new shape();
System.out.println(curr_shape.getPerimeter( <arguments> ));
}
}
}
You can use Class.forName() and reflection to create an instance, like #Milgo proposed, but I would recommend to create a simple switch/case. Your task looks like some training, so probably that would be best option for you.
Object form;
switch (type) {
case "Circle":
form = new Circle();
break;
case "Rectangle":
form = new Rectangle();
break;
}
Although you could use reflection (ie the dark arts), you can do it with minimal code if all shapes have the same constructor signature of say List<Double> (which includes integers like your example):
private static Map<String, Function<List<Double>, Shape>> factories =
Map.of("Circle", Circle::new, "Rectangle", Rectangle::new); // etc
public static Shape createShape(String input) {
String[] parts = input.split(" ");
String name = parts[0];
List<Double> dimensions = Arrays.stream(parts)
.skip(1) // skip the name
.map(Double::parseDouble) // convert String terms to doubles
.collect(toList());
return factories.get(name).apply(dimensions); // call constructor
}
interface Shape {
double getPerimeter();
}
static class Rectangle implements Shape {
private double height;
private double width;
public Rectangle(List<Double> dimensions) {
height = dimensions.get(0);
width = dimensions.get(1);
}
#Override
public double getPerimeter() {
return 2 * (height + width);
}
}
static class Circle implements Shape {
double radius;
public Circle(List<Double> dimensions) {
radius = dimensions.get(0);
}
#Override
public double getPerimeter() {
return (double) Math.PI * radius * radius;
}
}

Question about class and methods- create a object of the class inside a method

I am confusing when create an object inside a method.
For example in this coding; I am not sure why I am putting public void copiar(Ventana w) , why put this?? in the second method it's obvious because we are going to set this values to variables, but in the first method I don't have any idea what I am trying to do.
I hope someone can help me.
Class Ventana
{
public void copiar(Ventana w) {
}
public void copiar(String p, int xx, int y) {
}
}
Thanks in advance!
Reading between the lines, as it looks like you've not provided the full code, maybe you're trying to do this?
Class Ventana
{
string p;
int xx;
int y;
public static Ventana(Ventana w)
{
Ventana copy = new Ventana();
copy.p = w.p;
copy.xx = w.xx;
copy.y = w.y;
return copy;
}
}
It is like Elliott commented above.
With this method with Ventana as parameter it is more practical to duplicate a Ventana.
eg.:
Class Ventana{
private String style;
private int height;
private int wide;
public void copiar(Ventana w) {
this.style = w.getStyle();
this.height = w.getHeight();
this.wide = w.getWide();
}
public void copiar(String style, int height, int wide) {
//...
}
}
Probably, better to have the adequate constructor:
public Ventana (String style, int height, int wide){
this.style = style;
this.height = height;
this.wide = wide;
}
And then have the copy method as:
public Ventana copiar(Ventana w) {
return new Ventana(w.getStyle(), w.getHeight(), w.getWide());
}

How do I store objects of sub classes in array?

The question is to create objects of both sub classes and store them in an array .
So I create a abstract Super class and made a method area abstract after that I created the two sub classes and implemented that method on the main method I declared array and given the values this is it. I am new here so sorry if I'm asking it in wrong way.
And yes the output should be the area and types of two figure.
package Geometric;
public abstract class GeometricFigure {
int height;
int width;
String type;
int area;
public GeometricFigure(int height, int width) {
//super();
this.height = height;
this.width = width;
}
public abstract int area();
}
package Geometric;
public class Square extends GeometricFigure {
public Square(int height, int width) {
super(height,width);
}
public int area(){
return height * width;
}
}
package Geometric;
public class Triangle extends GeometricFigure {
public Triangle(int height, int width) {
super(height ,width);
}
public int area() {
return (height*width)/2;
}
}
package Geometric;
public class UseGeometric {
public static void main(String args[]) {
GeometricFigure[] usegeometric = { new Square(12, 15), new Triangle(21, 18) };
for (int i = 0; i < usegeometric.length; i++) {
System.out.println(usegeometric[i]);
usegeometric[i].area();
System.out.println();
}
}
}
You already are storing both elements in an array, I think your question is more related to this part:
usegeometric[i].area();
System.out.println();
You get the area of both elements, but you don't assign it to a variable, and you don't do anything with it. Change those lines of code to this:
System.out.println("Area: " + usegeometric[i].area());
EDIT:
Geometric.Square#19dfb72a Geometric.Triangle#17f6480
This is the kind of output you can expect because you didn't overwrite the toString method in your classes.
If you don't, it will take the inherited version of Object, which prints this information
--
In your Square class, add this:
public String toString() {
return "Square - area = " + area();
}
or something similar, depending on what you want to be printed. (And a similar adjustment to your Triangle class).
At this time, you are printing Object's version of toString, since you didn't provide a new one. By overwriting that method, you should get the output you want after turning your loop into:
for (int i = 0; i < usegeometric.length; i++) {
System.out.println(usegeometric[i]);
}
What println actually does, is not print the object itself, but a String representation of the object, which is provided by the toString method.
public class UseGeometric {
public static void main(String[] args) {
// TODO Auto-generated method stub
GeometricFigure[] usegeometric = { new Square(12, 15), new Triangle(21, 18) };
for (int i = 0; i < usegeometric.length; i++) {
System.out.println("Area is: " + usegeometric[i].area());
}
} }

Nullpointer Exception in function with 2d array as argument

I excepted that my functions in Level.java class allow me to make 2D array copy at any time in my program then change size of level array and fill it with values of copy and at last display it.
When I try to run my program it shows NullPointerException at line 24 in Level.java (a part which replaces the values).
Game.java Class
package main;
public class Game {
public static void main(String[] args) {
Level lvl = new Level();
char[][] exampleLevelTemplate = new char[][] {
{'#','#','#'},
{'#','#','#'},
{'#','#','#'}
};
lvl.setLevelSize(3,3);
lvl.setLevelLayout(exampleLevelTemplate);
lvl.displayLevel();
}
}
Level.java Class
package main;
public class Level {
private int levelWidth;
private int levelHight;
private char[][]level;
public void setLevelSize(int Width,int Height)
{
levelWidth = Width;
levelHight = Height;
char[][]level = new char[levelWidth][levelHight];
}
public void setLevelLayout(char[][]levelTemplate)
{
int a;
int b;
for(a=0; a < levelWidth; a++)
{
for(b=0; b<levelHight; b++)
{
level[a][b] = levelTemplate[a][b]; //Error happens here
}
}
}
public void displayLevel()
{
int a;
int b;
for(a=0; a < levelWidth; a++)
{
for(b=0; b<levelHight; b++)
{
System.out.println(level[a][b]);
}
}
}
}
Change your setLevelSize method to this:
public void setLevelSize(int Width,int Height)
{
levelWidth = Width;
levelHight = Height;
level = new char[levelWidth][levelHight];
}
You will see that line:
char[][]level = new char[levelWidth][levelHight];
was changed to:
level = new char[levelWidth][levelHight];
You need to just assign the array Object to array reference variable "level" and not create a local one and initialize it like you did.
You have been assigning value to a null array reference variable and therefore got NullPointerException.

How can I get my length and width to represented in a string format?

I was wondering if I could get some help with my length and width. I dont know how to get them into the format of being a string. I thought about the toString() idea, but then I think I would need a char value for that. Any help would be amazing.
public class Rectangle
{
// instance variables
private int length;
private int width;
/**
* Constructor for objects of class rectangle
*/
public Rectangle(int l, int w)
{
// initialise instance variables
length = l;
width = w;
}
// return the height
public int getLength()
{
return length;
}
public int getWidth()
{
return width;
}
public String String()
{
return System.out.println(length + " X " + width);
}
}
I have changed your String() method to toString() which I overrided. This method is used when we need a string representation of an object. It is defined in Object class. This method can be overridden to customize the String representation of the Object.You can check this
public class Rectangle
{
// instance variables
private int length;
private int width;
/**
* Constructor for objects of class rectangle
*/
public Rectangle(int l, int w)
{
// initialise instance variables
length = l;
width = w;
}
// return the height
public int getLength()
{
return length;
}
public int getWidth()
{
return width;
}
#Override
public String toString()
{
// TODO Auto-generated method stub
return length + " X " + width;
}
}
class Main{
public static void main(String[] args) {
Rectangle test = new Rectangle(3, 4);
System.out.println(test.toString());
}
}
Rename String() method to toString() (the method that normally returns an object string representation) and return from it length + " X " + width.
You can use String as a method name, but it violates JCC and looks abnormally.
Methods should be verbs, in mixed case with the first letter
lowercase, with the first letter of each internal word capitalized.
Examples:
run();
runFast();
getBackground();
Try this.
public class Rectangle {
// instance variables
private int length;
private int width;
/**
* Constructor for objects of class rectangle
*/
public Rectangle(int l, int w)
{
// initialise instance variables
length = l;
width = w;
}
// return the height
public int getLength()
{
return length;
}
public int getWidth()
{
return width;
}
#Override
public String toString()
{
return length + " X " + width;
}
public static void main(String[] args) {
Rectangle rec = new Rectangle(8, 9);
System.out.println(rec.toString());
}
}

Categories

Resources