I have written the instructions below and till now, I've came up with having two parameters and letting the method to assign the value and retrieving it. However, one of the instruction I had to follow was to include one constructor with no parameters, so I'm wondering what statement should I make inside the constructor without any parameters. It would be wonderful if anyone gives be a instruction. This is the code I've came up so far.
public class Rectangle {
//first constructor no parameters
//public<class name> (<parameters>)<statements>}
//two parameters one for length, one for width
//member variables store the length and the width
//member methods assign and retrieve the length and width
//returning the area and perimeter
static int recPerimeter(int l, int w) {
return 2*(l+w);
}
static int recArea(int l, int w) {
return l*w;
}
public static void main(String[] args) {
int p = recPerimeter(5, 3);
System.out.println("Perimeter of the rectangle : " + p);
int a = recArea(5,3);
System.out.println("Area of the rectangle : " + a);
}
}
First off, I would take some time to read the java tutorials. At least the "Covering the Basics"
There is a ton wrong with your example. You should store the the attributes of a rectangle - width and length as data members of the class which will get initialized with values through the constructors. If a default constructor is called with no values, then set the attributes to whatever you want. I set them to zero in the example.
Also, you need to normally create an instance of your class and then access it. Big red flag if you are having to prepend "static" to everything.
public class Rectangle {
private int recLength;
private int recWidth;
public Rectangle() {
recLength = 0;
recWidth = 0;
}
public Rectangle( int l, int w ) {
recLength = l;
recWidth = w;
}
public int calcPerimeter() {
return 2*(recLength+recWidth);
}
public int calcArea() {
return recLength*recWidth;
}
public static void main (String [] args) {
Rectangle rec = new Rectangle(5,3);
System.out.println("Perimeter = "+ rec.calcPerimeter());
System.out.println("area = " + rec.calcArea());
}
}
Related
I am having a warning: The assignment to variable length has no effect and default values in the output.If I add this keyword warnings disappears. Why this is happening?
This is my code
class Rectangle {
int length;
String breadth;
Rectangle(int length,String breadth)
{
length = length;
breadth = breadth;
}
}
class basic2 {
public static void main(String args[]) {
Rectangle r1 = new Rectangle(20,"hi");
System.out.println("Length of Rectangle : " + r1.length);
System.out.println("Breadth of Rectangle : " + r1.breadth);
}
}`
Your constructor parameters hide the class members since they have the same names. Therefore length = length; assigns a variable onto itself, which is meaningless.
To fix it, use the this keyword to refer to the class members :
Rectangle(int length,String breadth)
{
this.length = length;
this.breadth = breadth;
}
Because you are refering to the parameter of the constructor. Use this.length=length
while trying to get a grasp of polymorphism and inheritance, I made a small program to demonstrate these topics. The program consists of a superclass 'Tree' and three subclasses 'Birch', 'Maple', and 'Oak'. Tree's constructor makes it so that all trees start off with a height of 20 and 200 leaves. In Tree I have an abstract method called grow().
Here's the code for Tree:
public abstract class Tree {
private int height;
private int numberOfLeaves;
public Tree()
{
height = 20;
numberOfLeaves = 200;
}
public Tree(int aheight, int anum)
{
height = aheight;
numberOfLeaves = anum;
}
public int getHeight()
{
return height;
}
public int getNumberOfLeaves()
{
return numberOfLeaves;
}
public void setNumberOfLeaves(int anum)
{
numberOfLeaves = anum;
}
public abstract String getType();
public void setHeight(int aheight)
{
height = aheight;
}
public abstract void grow();
}
Here's the code in Birch for grow().
public void grow()
{
int height = super.getHeight();
super.setHeight(height++);
int num = super.getNumberOfLeaves();
super.setNumberOfLeaves(num+=30);
System.out.println("The Birch is Growing...");
}
However, when I call code to make an array of trees grow, none of their heights or number of leaves change.
Here's the code I used to populate the array of trees (I did it manually):
ArrayList<Tree> treeArray = new ArrayList<Tree>();
treeArray.add( new Oak());
treeArray.add(new Birch());
treeArray.add(new Maple());
And Here's the code I used to call grow:
for (Tree tree : treeArray)
{
tree.grow();
System.out.println("The " + tree.getType() + "'s height is " + tree.getHeight() + " and it's number of leaves is "+ tree.getNumberOfLeaves() +".");
}
Clearly, the values in the superclass aren't being modified. Any help will be appreciated! Thanks!
Change your code to :
int height = super.getHeight();
super.setHeight(++height);
note that you don't need to call super.method(). as long as the method is protected (public even better) you can just simplify it to :
int height = getHeight();
setHeight(++height);
You only call super. if you implement the method again in your child class and want to specifically call the parent class, which usually can be seen in constructor calling parent constructor.
One more thing : your accessor need to be changed a bit just for pre-caution case. see code below. Usually your IDE should support auto generation of accessor.
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
This code:
int height = super.getHeight();
super.setHeight(height++);
isn't going to change anything, because the increment of height will occur after the call to super.setHeight(). So you're just setting the height to its current value.
I have initialized the variables as follows in the code below. Is it okay to initialize like this ?
public class StaticInit {
int x = getInt();
String z = "Lucky Number " + processInt(x);
public static int getInt() {
int ret = 10;
System.out.println("ret- " + ret);
return ret;
}
public static int processInt(int toProcess) {
int toRet = toProcess / 2;
System.out.println("toRet- " + toRet);
return toRet;
}
public static void main(String[] args) {
StaticInit sit = new StaticInit();
}
}
You can initialise with the variable declaration or in the constructor. Some will argue that one or the other is better but either works. I believe the argument for initialise in the constructor is so that all variable initialisations are in the same place, since not everything can be initialised outside of the constructor in some cases.
public class StaticInit {
int x = getInt();
String z = "Lucky Number " + processInt(x);
}
or
public class StaticInit {
int x;
String z;
public StaticInit() {
x = 10;
z = x / 2;
}
}
For this case in particular though, I would definitely recommend using the constructor since z relies on x. Plus the constructor is much nicer than using static methods.
Personally, instead of having the getInt(), I would just initialise it in the constructor.
Unless you're going to use the getInt() function externally, I don't see the point in having it, especially since it returns a hardcoded value.
Can we swap two numbers in Java using pass by reference or call by reference?
Recently when I came across swapping two numbers in Java I wrote
class Swap{
int a,b;
void getNos(){
System.out.println("input nos");
a = scan.nextInt();
b = scan.nextInt(); // where scan is object of scanner class
}
void swap(){
int temp;
temp = this.a;
this.a = thisb;
this.b = this.a;
}
}
In the main method I call the above mentioned methods and take two integers a,b and then using the second method I swap the two numbers, but relative to the object itself....
Does this program or logic come under pass by reference?
And is this correct solution?
Yes and no. Java never passes by reference, and your way is one workaround. But yet you create a class just to swap two integers. Instead, you can create an int wrapper and use pass it, this way the integer may be separated when not needed:
public class IntWrapper {
public int value;
}
// Somewhere else
public void swap(IntWrapper a, IntWrapper b) {
int temp = a.value;
a.value = b.value;
b.value = temp;
}
As the comments show, I might not have been clear enough, so let me elaborate a little bit.
What does passing by reference mean? It means that when you pass an argument to the method, you can change the original argument itself inside this method.
For example, if Java was pass-by-reference, the following code will print out x = 1:
public class Example {
private static void bar(int y) {
y = 10;
}
public static void main(String[] args) {
int x = 1;
bar(x);
System.out.println("x = " + x);
}
}
But as we know, it prints 0, since the argument passed to the bar method is a copy of the original x, and any assignment to it will not affect x.
The same goes with the following C program:
static void bar(int y) {
y = 1;
}
int main(int argc, char * argc[]) {
int x = 0;
bar(x);
printf("x = %d\n", x);
}
If we want to change the value of x, we will have to pass its reference (address), as in the following example, but even in this case, we will not pass the actual reference, but a copy of the reference, and by dereferencing it we will be able to modify the actual value of x. Yet, direct assignment to the reference will no change the reference itself, as it is passed by value:
static void bar(int &y) {
*y = 1;
y = NULL;
}
int main(int argc, char * argc[]) {
int x = 0;
int * px = &x;
bar(px);
printf("x = %d\n", x); // now it will print 1
printf("px = %p\n", px); // this will still print the original address of x, not 0
}
So passing the address of the variable instead of the variable itself solves the problem in C. But in Java, since we don't have addresses, we need to wrap the variable when we want to assign to it. In case of only modifying the object, we don't have that problem, but again, if we want to assign to it, we have to wrap it, as in the first example. This apply not only for primitive, but also for objects, including those wrapper objects I've just mentioned. I will show it in one (longer) example:
public class Wrapper {
int value;
private static changeValue(Wrapper w) {
w.value = 1;
}
private static assignWrapper(Wrapper w) {
w = new Wrapper();
w.value = 2;
}
public static void main(String[] args) {
Wrapper wrapper = new Wrapper();
wrapper.value = 0;
changeValue(wrapper);
System.out.println("wrapper.value = " + wrapper.value);
// will print wrapper.value = 1
assignWrapper(w);
System.out.println("wrapper.value = " + wrapper.value);
// will still print wrapper.value = 1
}
}
Well, that's it, I hope I made it clear (and didn't make too much mistakes)
import java.util.*;
public class Main
{
int a,b;
void swap(Main ob)
{
int tmp=ob.a;
ob.a=ob.b;
ob.b=tmp;
}
void get()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a and b: ");
a=sc.nextInt();
b=sc.nextInt();
}
public static void main(String[] args) {
Main ob=new Main();
ob.get();
ob.swap(ob);
System.out.println(ob.a+" "+ob.b);
}}
I am trying to return two numbers from this method. I thought this was correct. Where am I going wrong?
public int[] getDimension() {
int shapeWidth = 0;
int shapeHeight = 0;
// .....
int[] result = new int[] {shapeWidth, shapeHeight};
return result;
}
And then at a calling site, is this correct?
public int getWidth() {
return getDimension()[0];
}
I am asking because I believe there's a bug but I don't see it.
That's fine. Short but complete program to demonstrate it working:
public class Test {
public static void main(String args[]) {
int width = getDimension()[0];
System.out.println(width);
}
public static int[] getDimension() {
int shapeWidth = 5;
int shapeHeight = 10;
int[] result = new int[] {shapeWidth, shapeHeight};
return result;
}
}
You can make the result declaration line slightly simpler, by the way:
int[] result = {shapeWidth, shapeHeight};
Rather than using an array, I would recommend using a class
class Dimensions {
private int width;
private int height;
public Dimensions(int width, int height) {
this.width = width;
this.height = height;
}
// add either setters and getters
// or better yet, functionality methods instead
}
This will give you compile time referential integrity, which is much better than inferring based on "we know index 0 is width and index 1 is height".
If you still want to use an array, Jon's answer is spot on.
Your code looks fine, but try not to use an array if you only need a pair.
Since Java doesn't have tuples/pairs you have to implement them, but it's pretty easy. Refer to this question for a possible implementation.
public class Test {
public static void main(String args[]) {
int width = getDimension().getLeft();
System.out.println(width);
}
public static Pair<Integer, Integer> getDimension() {
int shapeWidth = 5;
int shapeHeight = 10;
return new Pair<Integer, Integer>(shapeWidth, shapeHeight);
}
}
This is better than a Dimension class, because you can use it everywhere in your code.