I got this task and I can't quite figure out how to solve it:
"Change all three of the x-variables related to the C-class."
class A {
public int x;
}
class B extends A {
public int x;
}
class C extends B {
public int x;
public void test() {
//There are two ways to put x in C from the method test():
x = 10;
this.x = 20;
//There are to ways to put x in B from the method test():
---- //Let's call this Bx1 for good measure.
---- //Bx2
//There is one way to put x in A from the method test();
---- //Ax1
}
}
To test, I set up this:
public class test {
public static void main(String[] args)
{
C c1=new C();
c1.test();
System.out.println(c1.x);
B b1=new B();
System.out.println(b1.x);
A a1=new A();
System.out.println(a1.x);
}
}
Which gives 20, 0, 0.
Now, I figured out I could write Bx1 like this:
super.x=10;
That would change the x in B, but I could not figure out how to call it in my test.java.
How do you get Bx1, Bx2, Ax1, and how do you call them for a test?
You can access the superclass's version of x by using a superclass type reference:
System.out.println("A's x is " + ((A)this).x);
That will get A#x.
But in general, it's a very bad idea to shadow a superclass's public instance members.
Example: (live copy on IDEOne)
class Example
{
public static void main (String[] args) throws java.lang.Exception
{
new C().test();
}
}
class A {
public int x = 1;
}
class B extends A {
public int x = 2;
}
class C extends B {
public int x = 3;
public void test() {
//There are two ways to put x in C from the method test():
System.out.println("(Before) A.x = " + ((A)this).x);
System.out.println("(Before) B.x = " + ((B)this).x);
System.out.println("(Before) C.x = " + this.x);
((A)this).x = 4;
System.out.println("(After) A.x = " + ((A)this).x);
System.out.println("(After) B.x = " + ((B)this).x);
System.out.println("(After) C.x = " + this.x);
}
}
Output:
(Before) A.x = 1
(Before) B.x = 2
(Before) C.x = 3
(After) A.x = 4
(After) B.x = 2
(After) C.x = 3
this is how your test method could look like
void test() {
this.x = 30;
A a = this;
a.x = 10;
B b = this;
b.x = 20;
}
It´s important to note, that you are accessing the variable of the Type of the class that you defined, so in that case you would Access, x from A, and x from B by defining a variable due to the this keyword.
Using getters and setters
class A {
public int x;
}
class B extends A {
public int x;
public void setAx(int x) {
super.x = x;
}
public int getAx() {
return super.x;
}
}
class C extends B {
public int x;
public void test() {
x = 10;
this.x = 20;
}
public void setBx(int x){
super.x = x;
}
public int getBx() {
return super.x;
}
public static void main(String[] args)
{
C c1= new C();
c1.x = 1;
c1.setAx(2);
c1.setBx(3);
System.out.println(c1.getAx()+"/"+c1.getBx()+"/"+c1.x);
}
}
Related
I have 3 classes, among the classes, I am trying to play with methods for that from Second class I am passing some values into First class and from there I am passing values to third class
in the Third I am combining 3 parameters and storing in a variable called p.
now I am trying to print p value in Second class using a method which returns p value but it printing as zero but in the setFive() method it printing the actual value.
Please help me with this where i am doing wrong
Tried Code:
class First {
int x, y, z;
void setOne(int a, int b, int c) {
a = a + x;
b = b + y;
c = c + z;
Third obj = new Third();
obj.setFive(a, b, c);
}
void two(int a) {
this.x = a;
}
void three(int a) {
this.y = a;
}
void four(int a) {
this.z = a;
}
}
class Second {
public static void main(String args[]) {
First f = new First();
f.two(100);
f.three(150);
f.four(170);
f.setOne(1, 2, 3);
Third obj = new Third();
System.out.println(obj.getFive());
}
}
class Third {
int p;
public void setFive(int a, int y, int n) {
this.p = a + y + n;
}
public int getFive() {
return p;
}
}
Thanks
When you do Third obj = new Third(); inside first.setOne(int a,int b,int c), this obj is local to that method, no other object can see it. It is destroyed when the code exits that method
What you need to do it create that Third object in your Second class, and then pass it to First:
Third obj = new Third();
f.setOne(obj, 1, 2, 3);
then on First you need to change the signature to take the object, and call the setter on it:
void setOne(Third obj, int a, int b, int c) {
a = a + x;
b = b + y;
c = c + z;
obj.setFive(a, b, c);
}
I am in process of learning immutability but I am not able to exactly digest how this works. So in order for me to understand immutability, I created a test program.
The funtion getArray(Box b) will make an ArrayList of Box objects.
Expected output: Actual output:
Output Output
a is 5 a is 5
b is 10 b is 10
Output Output
a is 0 a is 4
b is 0 b is 40
Output Output
a is 1 a is 4
b is 10 b is 40
Output Output
a is 2 a is 4
b is 20 b is 40
Output Output
a is 3 a is 4
b is 30 b is 40
Output Output
a is 4 a is 4
b is 40 b is 40
Logic:
public class Box {
static int a;
static int b;
public Box() {
a = 5;
b = 10;
}
public int getA() {
return a;
}
public void setA(int x) {
a = x;
}
public int getB() {
return b;
}
public void setB(int x) {
b = x;
}
public void display() {
System.out.println("Output");
System.out.println("a is " + a);
System.out.println("b is " + b);
System.out.println();
}
}
Main Class
import java.util.ArrayList;
public class Check {
public static void main(String[] args) {
Box b = new Box();
b.display();
ArrayList<Box> arr2 = new ArrayList<Box>();
arr2 = getArray(b);
for (int i = 0; i < arr2.size(); i++) {
arr2.get(i).display();
}
}
public static ArrayList<Box> getArray(Box b) {
ArrayList<Box> arr = new ArrayList<Box>();
for (int i = 0; i < 5; i++) {
b.setA(i);
b.setB(i * 10);
arr.add(b);
}
return arr;
}
}
How do I change the logic in such a way that I get the desired output? How do we decide how and where to edit the code to ensure immutability?
This would be an immutable:
public final class Box {
final int a;
final int b;
public Box(int a, int b) {
this.a = a;
this.b = b;
}
}
And then your array method would be:
public static ArrayList<Box> getArray(Box b) {
ArrayList<Box> arr = new ArrayList<Box> ();
for(int i =0 ;i <5; i++) {
arr.add(new Box(i, i*10));
}
return arr;
}
The data members are declared final because they're immutable, and so getters are pointless and setters just make no sense.
The class is declared final so you cannot subclass it.
In short, an immutable object is an object whose state cannot be modified after it's created. Your immutable Box object would look like this:
public final class Box {
private final int a;
private final int b;
public Box(int a, int b) {
this.a = a;
this.b = b;
}
public int getA() {
return a;
}
public int getB() {
return b;
}
public void display() {
System.out.println("Output");
System.out.println("a is " + a);
System.out.println("b is " + b);
System.out.println();
}
}
Notice that the variables a and b are assigned exactly once, during the construction of the Box instance. There are no setters, because Box's immutability means that its state (including variables a and b) will not change over its lifetime.
The final keyword in front of a and b means that you must assign them exactly once. It's actually considered good practice to make all your variables final unless you specifically need them not to be; but for an immutable object it's essential.
You were using the static keyword. Static has nothing to do with immutability. It means the variable is shared among all instances of the Box class. In my example, each Box instance has its own copies of a and b, because I didn't make them static.
To wrap this up, I'll give an example of your main class which has the desired output:
public class Check {
public static void main(String[] args) {
final List<Box> arr2 = getArray();
for (int i = 0; i < arr2.size(); i++) {
arr2.get(i).display();
}
}
public static ArrayList<Box> getArray() {
final ArrayList<Box> arr = new ArrayList<>();
for (int i = 0; i < 5; i++) {
final Box box = new Box(i, i * 10);
arr.add(box);
}
return arr;
}
}
Note that a new instance of box is created at every iteration of the loop.
Please run output of below two programs...
Program_1:
package p1;
class x {
public void methodA() {
System.out.println("Methos A of Class X");
}
}
class y extends x {
public void methodA() {
System.out.println("Method A of Class Y");
}
}
class Override1 {
public static void main(String[] args) {
x obj1 = new x();
x obj2 = new y();
y obj3 = new y();
/* y obj4 = new x(); */
obj1.methodA();
obj2.methodA();
obj3.methodA();
/* obj4.methodA(); */
}
}
Program_2 :
class x {
int a[] = new int[2];
x() {
a[0] = 10;
a[1] = 20;
}
}
class y extends x {
int a[] = new int[10];
y() {
a[0] = 12000;
a[1] = 1000;
a[2] = 120;
}
}
class Override2 {
public static void main(String[] args) {
x obj1 = new x();
x obj2 = new y();
// y obj3 = new x();
y obj4 = new y();
System.out.println(obj1.a[1]);
System.out.println(obj2.a[1]);
System.out.println(obj4.a[1]);
}
}
My specific question is that in Program_1 by what means MethodA of class Y Called? and in program_2 by What means '20' (a[1]) of class X is called?
please clear my basic concept about creation of object regarding memory allotment and reference assignment.
The short answer is that there is no data polymorphism in Java.
In the first example, methodA is the same method implemented in different classes.
In the second example, the two a are completely separate, unrelated data members (even though they happen to have the same name and data type).
The second example is equivalent to:
class x {
int a_x[] = new int[2];
x() {
a_x[0] = 10; a_x[1] = 20;
}
}
class y extends x {
int a_y[] = new int[10];
y() {
a_y[0] = 12000; a_y[1] = 1000; a_y[2] = 120;
}
}
class Override2 {
public static void main(String[] args) {
x obj1 = new x();
x obj2 = new y();
y obj4 = new y();
System.out.println(obj1.a_x[1]);
System.out.println(obj2.a_x[1]);
System.out.println(obj4.a_y[1]);
}
}
My specific question is that in Program_1 by what means MethodA of class Y Called? --> Its called Dynamic Dispatch mechanism (Method overriding). check here. Here, the method of the RHS (instance type) is called irrespective of the reference on the LHS (child / parent), provided the parent defines the same method.
What means '20' (a[1]) of class X is called --> depends on the type of reference. If reference is of X x.field is called irrespctive of RHS.
I'm stuck on a mock exam question. I created a class called Power which allowed a number to be raised to any power.
The third part of the question asks me to create another class BoundedPower which would extend Power. I was given the MAX-X variable (x cannot exceed this value) and told that the BoundedPower class must: behave like the Power class, use a constructor and use thepowN method.
My code is below, i am not sure what to do to make the BoundedPower class work.
public class Power {
private double x = 0;
Power(double x) {
this.x = x;
}
public double getX() {
return x;
}
public double powN(int n) {
double result = 1.0;
for (int i = 0; i < n; i++) {
result = result * x;
}
return result;
}
public static void main(String[] args) {
Power p = new Power(5.0);
double d = p.powN(3);
System.out.println(d);
}
}
public class BoundedPower extends Power {
public static final double MAX_X = 1000000;
// invariant: x <= MAX_X
Power x;
BoundedPower(double x) {
super(x);
// this.x=x; x is private in Power class
}
public double powN(int n) {
if (x.getX() > MAX_X) {
return 0;
} else {
double result = 1.0;
for (int i = 0; i < n; i++) {
result = result * getX();
}
return result;
}
}
public static void main(String[] args) {
BoundedPower bp = new BoundedPower(5);
double test = bp.powN(4);
System.out.println(test);
}
}
There is no need for that instance Power variable x in your class. Any BoundedPower instance IS a Power instance, and as such, to reference a method from Power, do super.blah(), so for x.getX(), do super.getX()
Also, in your comments, you said this.x=x fails because its private. When you do the super call, it calls the constructor of the superclass (Power), which sets x there, so there is no need for this.x=x
public class BoundedPower extends Power {
public static final double MAX_X = 1000000;
BoundedPower(double x) {
super(x);
}
public double powN(int n) {
if (x.getX() > MAX_X) {
return 0;
} else {
return super.powN(n);
}
}
public static void main(String[] args) {
BoundedPower bp = new BoundedPower(5);
double test = bp.powN(4);
System.out.println(test);
}
}
You don't have to copy your computation formular to the subclass (just call super.powN(..)). You also don't need another instance of Power within BoundedPower.
This is probably what they had in mind:
public class Power {
public double powN(double x, int n) {
double result = 1.0;
for (int i = 0; i < n; i++) {
result = result * x;
}
return result;
}
}
public class BoundedPower extends Power {
private final double maxX;
public BoundedPower(double maxX) {
this.maxX = maxX;
}
public double powN(double x, int n) {
if (x > maxX) {
throw new IllegalArgumentException("x value [" + x + "] " +
"greater than expected max [" + maxX + "]");
}
return super.powN(x, n);
}
}
I would do it in a different way. From what you're saying the BoundedPower class makes sense only for a bounded x (up to MAX_X).
Consequently, I would not allow the creation of an object with an x greater than MAX_X (i.e. a BoundedPower object cannot exist for unbounded x's)
So the implementation would be exactly as the the Power implementation excepting the way you build BoundedPower instances : you first check whether it makes sense to build it
public class BoundedPower extends Power {
private static final double MAX_X = 1000000; //makes no sense to be public
public static BoundedPower newBoundedPower(int n)
throws IllegalNumberException{
if(x > MAX_X) throw new IllegalNumberException();
return new BoundedPower(x);
}
private BoundedPower(double x) {
super(x);
}
}
Hi im new to this site and need help with a program im working on. the problem im having is that i cant seem to store string and two integers (as the coordinates). i have looked at other code but dont see how the values are stored. below is the code ive been using. the code seems to be fine but when trying to stored the values i cant put multiply integers. thanks for your time
import java.util.HashMap;
public class map {
class Coords {
int x;
int y;
public boolean equals(Object o) {
Coords c = (Coords) o;
return c.x == x && c.y == y;
}
public Coords(int x, int y) {
super();
this.x = x;
this.y = y;
}
public int hashCode() {
return new Integer(x + "0" + y);
}
}
public static void main(String args[]) {
HashMap<Coords, Character> map = new HashMap<Coords, Character>();
map.put(new coords(65, 72), "Dan");
}
}
There is a class in java called Class Point.
http://docs.oracle.com/javase/7/docs/api/java/awt/Point.html
This is the same information provided on Java docs API 10:
https://docs.oracle.com/javase/10/docs/api/java/awt/Point.html
A point representing a location in (x,y) coordinate space, specified in integer precision.
You can see an example, and also other important topics related in this link: http://www.java2s.com/Tutorial/Java/0261__2D-Graphics/Pointclass.htm
import java.awt.Point;
class PointSetter {
public static void main(String[] arguments) {
Point location = new Point(4, 13);
System.out.println("Starting location:");
System.out.println("X equals " + location.x);
System.out.println("Y equals " + location.y);
System.out.println("\nMoving to (7, 6)");
location.x = 7;
location.y = 6;
System.out.println("\nEnding location:");
System.out.println("X equals " + location.x);
System.out.println("Y equals " + location.y);
}
}
I hope this can help you!
There seems to be several issues:
"Dan" is a String, not a Character
case is important in Java (new coords(65,72) should be new Coords(65,72))
Coords needs to be static to be instantiated without a reference to an instance the enclosing map class.
This should work:
static class Coords {
...
}
Map<Coords, String> map = new HashMap<Coords, String>();
map.put(new Coords(65, 72), "Dan");
ps: although you are allowed to name a local variable map within a class map, it is not a good idea to have such name collision. In Java, classes generally start in upper case, so you could rename your class Map. But it happens that Map is a standard class in Java. So call your class Main or Test or whatever is relevant. ;-)
Adding to #assylias
Make you inner class static in order to insert new objects like you have or new Outer().new Inner() .
Take care of Java Naming Convention
Code like:
public class XYTest {
static class Coords {
int x;
int y;
public boolean equals(Object o) {
Coords c = (Coords) o;
return c.x == x && c.y == y;
}
public Coords(int x, int y) {
super();
this.x = x;
this.y = y;
}
public int hashCode() {
return new Integer(x + "0" + y);
}
}
public static void main(String args[]) {
HashMap<Coords, String> map = new HashMap<Coords, String>();
map.put(new Coords(65, 72), "Dan");
map.put(new Coords(68, 78), "Amn");
map.put(new Coords(675, 89), "Ann");
System.out.println(map.size());
}
}
package Lecture3;
import java.util.Scanner;
public class lecture9 {
private int nInleste;
public lecture9() {/*
* tabell/ // T/*chapter 6 in the books.
**/
}
public static void main(String[] args) {
Scanner inn = new Scanner(System.in);
int nInleste = 3;
double[] tall = new double[nInleste];
double sum = 0;
for (int i = 0; i < nInleste; i++) {
System.out.println("Leste en tall!");
tall[i] = inn.nextDouble();
sum += tall[i];
}
System.out.println(sum);
double snitt = nInleste / nInleste;
System.out.println("Gjennomsnittsverdien:" + snitt);
for (int i = 0; i < nInleste; i++) {
double aavik = tall[i] - snitt;
int avvivk = 0;
System.out.println(i + 1 + " Tal sitt avvik fra gjennomsnittet " + avvivk);
}
}/* end of the main methods */
}
if you have problem with your code you can try this , simple code to store string and two int values into a map
class MyCoord{
private int X;
private int Y;
public MyCoord() {
this(0,0);
}
public MyCoord(int X, int Y) {
this.X = X;
this.Y = Y;
}
public int getX() {
return X;
}
public int getY() {
return Y;
}
public void setX(int X) {
this.X = X;
}
public void setY(int Y) {
this.Y = Y;
}
}
//main class begins
public class PointDemo{
public static void main(String[] args) {
Map <String,MyCoord> multiplePoints=new HashMap<String, MyCoord>();
multiplePoints.put("point1", new MyCoord(10, 20));
multiplePoints.put("point2", new MyCoord(100, 2000));
MyCoord coord=multiplePoints.get("point1");
System.out.println(coord.getX() +" : "+coord.getY());
}
}