Getting value from constructor in another class - java

I am sure this is a very easy question for many, but I am struggling with it. I am trying to get a value from the following constructor and place it in a vector.
Each time I add the object to the vector though, the value that is placed inside the vector is null. How can I get the number to be the value that is placed into the vector?
The CInteger class:
public class CInteger
{
private int i;
CInteger(int ii)
{
i = ii;
}
}
And in my A1 class, the constructor and my attempt at getting the value:
Object enqueue(Object o)
{
CInteger ci = new CInteger(88);
Object d = ??
add(tailIndex, d);// add the item at the tail
}
Thank you all for any insight and help, I am still learning.
EDIT: SOLVED
CInteger class:
public class CInteger implements Cloneable // Cloneable Integer
{
int i;
CInteger(int ii)
{
this.i = ii;
}
public int getValue()
{
return i;
}
}
Both enqueue methods:
public void enqueue(CInteger i) // enqueue() for the CInteger
{
add(tailIndex, new Integer(i.getValue())); get int value and cast to Int object
}
public void enqueue(Date d) // enqueue() for the Date object
{
add(tailIndex, d);
}
Thank you very much everyone. :D

You can simply overload the enqueue class to take both Dates and Integers. In either case, it sounds like you need a method getValue() in CInteger that lets you access the int value.
public class CInteger
{
//constructors, data
public void getValue()
{
return i;
}
}
and then you can have two enqueue() methods in your other class:
public void enqueue(Date d)
{
add(tailIndex, d);
}
public void enqueue(CInteger i)
{
add(tailIndex, new Integer(i.getValue()); //access the int value and cast to Integer object
}
And Java will know which one you are calling automatically based on the parameters.

It is not entirely clear what you are actually trying to do, but I think that this will suffice:
Object enqueue() {
CInteger ci = new CInteger(88);
add(tailIndex, ci);// add the item at the tail
return ci; // this will automatically upcast ci as an Object
}

Try this.
public class CInteger {
private int i;
CInteger(int ii) {
this.i = ii;
}
}
Using the this Keyword

First of all, Constructors never return any value. You have to access the value through its objects or you have to use getter methods.
In your case, "private int i;" can not be accessed directly. So try make either it as public or have some getter method.
So try it:
CInteger ci = new CInteger(88);
Object d = ci.i; // if i is public member
add(tailIndex, d);
or
...
private int i;
...
public int getI() {
return this.i;
}
...
CInteger ci = new CInteger(88);
Object d = ci.getI();
add(tailIndex, d);

Wouldn't it just be:
void main(string[] args)
{
CInteger ci = new CInteger(88);
encqueue(ci.i);
}
Object enqueue(Object o)
{
add(tailIndex, o);
}
Or am I missing something?

Related

Polymorphic Misunderstand

When i call s1.dub(7) or s2.dub(7) it doesn't work
,but calling it with a string like s2.dub("9") works and prints the doubled string
Could any one tell me why?
Here's the code
interface Inter {
int number();
}
abstract class Abs {
static int foo = 12;
int number() { return 5; }
abstract int ace();
}
final class Sub extends Super {
Sub(int bar) { foo = bar; }
public int number() { return 10; }
int ace() { return 13; }
int dub(int i) { return 2 * i; }
}
public class Super extends Abs implements Inter {
public int number() { return 11; }
public static void main(String args[]) {
Super s1 = new Super();
Super s2 = new Sub(16);
//System.out.println(s1.dub(7)); //doesn't work
//System.out.println(s2.dub(7)); //doesn't work
//System.out.println(s1.dub("7")); //works giving 77
//System.out.println(s2.dub("7")); //works giving 77
}
int twice(int x) { return 2 * x; }
public int thrice(int x) { return 3 * x; }
int ace() { return 1; }
String dub(String s) { return s + s; }
}
Very easy.. you class Super defines a method:
String dub(String s) { return s + s; }
in your main method you instantiate Super:
Super s1 = new Super(); // this has a dub( String ) method
then you try to call this method (dub) passing a integer, instead of a string:
System.out.println(s1.dub(7)); // s1.dub(...) takes a String, not a number
EDIT: This code should not compile, or run, because you are assigning both instances to the super class Super (which does not define a dub(int) method).
Not sure how you are getting exceptions?
Thank you #Jean-FrançoisSavard - I totally missed that!
EDIT2: The original question was modified and no longer indicates that an exception is thrown, which makes sense as the code should not compile at all.
EDIT3: (last one, due to original question changing)
System.out.println(s1.dub(7)); //- this will never work unless you change your class' definition
System.out.println(s2.dub(7)); //- will work if you also change the following line:
from:
Super s2 = new Sub(16);
to:
Sub s2 = new Sub(16);

Looping through set

I create two classes. The first one (call it Class1) has one private attribute: price. The second one (call it Class2) needs to have a set of objects of Class1:
My code:
private HashSet set = new HashSet<Class1>();
The goal is to create a method in the Class2, which takes an int as an argument and goes through objects to check until it finds one, which has a price equal to a given as an argument number. It needs to return the object. For example, I want to find an object with a price of 500, so I call the function check(500) and it returns exactly that object, which has price of 500. How can I do it?
My code:
public Class1 check(int p)
{
Class1 c = new Class1(p);
Iterator it = set.iterator();
while(it.hasNext())
{
// HERE IS THE HELP NEEDED. Using an array it
// would be sth like if(element[i].price == p)
// but I need to use set
if()
{}
it.next();
}
You can do it like so - however you will need access to the price to be able to compare it. If price itself is private, there should be a getter for it, which I assume in my solution.
public Class1 check(int p) {
for (Class1 c : set) {
if (c.getPrice() == p) return c;
}
return null; // none found
}
In your class Class1, define a getter method
int getPrice() { return price; }
Use it in your class Class2
Class1 curObj = it.next();
if (curObj.getPrice() == p) {
your logic
}
Something like this should work:
public Class1 check(int p) {
Iterator<Class1> it = set.iterator();
while (it.hasNext()) {
Class1 next = it.next();
if (next.getPrice() == p) {
return next;
}
}
return null;
}
I assumed your class Class1 has a getPrice method that returns the price, it is ofcourse impossible to compare the price that we need to find to the price of an object if there is no way to access the field.
Your generic type declaration is incorrect and thus you have a raw type; and you should prefer the Set interface. Something like
private Set<Class1> set = new HashSet<>();
And you can use an enhanced for-each loop to iterate your set items and find a matching price with something like
public Class1 check(int p) {
for (Class1 item : set) {
if (item.getPrice() == p) {
return item;
}
}
return null;
}
Whenever you have private variables, expose them through getter function.
Setters and getters will always help you whenever you will write code with some frameworks like Spring, Hibernate, etc.
public class class2 {
private HashSet set = new HashSet<Class1>();
public Class1 check(int price) {
Iterator<Class1> iterator = set.iterator();
while(iterator.hasNext()) {
Class1 next = iterator.next();
if(next.getPrice() == price)
return next;
}
return null;
}
}
class Class1 {
private int price;
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
You can it iterate the set and in every iteration compare the object against the price parameter, if found return the object, if not return null
Example
public Class1 check(int p)
{
for(Class c : set){
if(c.getPrice ()==p){
return c;
}
}
return null;
}
Add a getter of the price attribute in class1, then the check method can be as follows:
public Class1 check(int p)
{
for (Class1 c1 : set)
{
if (c1.getPrice() == p)
return c1;
}
return null
}

How can I get subclass value from super class method in Java?

I have these two classes:
Class A
{
public int max = 100;
public int getMax()
{
return max;
}
}
Class B extends A
{
public int max = 200;
}
I write the following code:
A clsA = new A();
B clsB = new B();
valA = clsA.getMax();
valB = clsB.getMax();
valA is 100
valB is 100 again
How can I write code that clsB.getMax(); returns 200?
You can override getMax in class B:
#Override
public int getMax()
{
return max;
}
Though, in general, it's a bad idea to have variables with the same name in the super class and the sub-class.
Note that after the change, the following will also return 200 :
A clsB = new B();
valB = clsB.getMax();
Override the getMax method in B:
class B extends A
{
public int max = 200;
public int getMax()
{
return max;
}
}
In the getter method, return max; is equivalent to return this.max where this references the current instance of B. On the other hand, calling return super.max returns the max field value referenced in the parent subclass.
the short answer is that you can't override members in subclasses like you are trying. What you instead should do is make B change the value of max directly. Something like this:
class B extends A
{
public B()
{
max = 200;
}
}
You have to add method getMax() to class B. The implementation might be the same as in Class A
#Overwrite
public int getMax()
{
return max;
}
When you DO NOT overwrite the method one from B calls parent's method getMax(). And parent metod getMax() returns 150
Try Method Overriding
In Java, the "closest method" will be called. Because clsB extends A, but doesn't have it's own definition of getMax(), A's version of getMax() will be called. However, because clsB also shares the variables of A, getMax (called from class A) will return class A's number.
The solution?
add
public int getMax()
{
return max;
}
to class B.
Implement Method override concept
#Override
public int getMax()
{
return max;
}
Overriding happens at run time
A clsB = new B();
valB = clsB.getMax();
Hope this should work.
Java does not support override any variables in a class.
You can have two ways to do it.
Pass the variable through a constructor. I suggest doing this way because, if the method do the same action. By overriding it and doing it again is a bad practice.
Class A {
public int max = 100;
public A(int maxVal)
{
this.max=maxVal;
}
public int getMax(){
return max;
}
}
B clsB = new B();
A clsA = new A(clsB.max);
Override the method
#override
public int getMax(){
max=200;
//do the job.
}

List add function does not operate properly?

public static void main(String[] args) {
// TODO Auto-generated method stub
List<item> l = new ArrayList<item>();
List<Integer> ll = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
l.add(new item(i,i));
ll.add(i);
}
System.out.println(l.get(4).getWeight());
System.out.println(ll.get(4));
}
public class item {
private static int value;
private static int weight;
public item(int val, int w) {
setValue(val);
setWeight(w);
}
public static int getValue() {
return value;
}
public static void setValue(int value) {
item.value = value;
}
public static int getWeight() {
return weight;
}
public static void setWeight(int weight) {
item.weight = weight;
}
}
This is my code, and then item is class take two paratemers. But when I add the item into list, the elelments in list have same value(in this case it is 9). For Integer, there is no problem. I think I miss some critical parts of java feature.
Any help appreciated, thank you in advance.
All of your methods and members of item are static. That is, they belong to the item class, rather than a specific instance of that class. The static members are shared among every instance of the class, and so every new item you create is using the same set of data. You will want to make them not be static.
Check out the following official tutorials for more info, they are concise and well-written and will help you:
Non-static, member variables: Declaring Member Variables
Non-static, methods: Defining Methods
static class members: Understanding Class Members
Once you have done this, as Takendarkk astutely points out in a comment, be sure to use this.value = ... instead of item.value = ... (no longer valid) or value = ... (uses local scope value instead of member).

Java consecutive method calls

So I've seen, in many places, calling methods of a class like:
SomeClass obj = new SomeClass();
obj.addX(3).addY(4).setSomething("something").execute();
I don't think I completely understand how that works. Is each method independent of each other, so the above is equal to:
obj.addX(3);
obj.addY(4);
obj.addSomething("something");
obj.execute();
Or are they designing their class structure in some other fashion that allows for this. If they are how are they designing their classes to support this?
Also, does that have a specific name? Or is this just calling methods on a class?
That would be method chaining. It can do one of two things.
Each call to a method returns this which allows you to continue to call methods on the original instance.
public class SomeClass
{
private int _x = 0;
private int _y = 0;
private String _something = "";
public SomeClass addX(int n)
{
_x += n;
return this;
}
public SomeClass addY(int n)
{
_y += n;
return this;
}
public SomeClass setSomething(String something)
{
_something = something;
return this;
}
// And so on, and so on, and so on...
}
Each method call returns a new instance of the class with everything copied/updated appropriately. This makes the class immutable (so you don't accidentally modify something that you didn't mean to).
public class SomeClass
{
private int _x = 0;
private int _y = 0;
private String _something = "";
public SomeClass(int x, int y, String something)
{
_x = x;
_y = y;
_something = something;
}
public SomeClass addX(int n)
{
return new SomeClass(_x + n, _y, _something);
}
public SomeClass addY(int n)
{
return new SomeClass(_x, _y + n, _something);
}
public SomeClass setSomething(String something)
{
return new SomeClass(_x, _y, something);
}
// And so on, and so on, and so on...
}
Some people have also mentioned Fluent Interfaces. Fluent Interfaces utilize method chaining to create an API that provides something along the lines of a Domain Specific Language which can make code read much more clearly. In this case, your example doesn't quite qualify.
they modify object's state and return the same object back mostly
class Number{
int num;
public Number add(int number){
num+=number;
return this;
}
}
you can call it like
new Number().add(1).add(2);
most of the time the use case is to return new Object to support immutability
Each of those methods return an instance. For example, the call to
obj.addX(3)
will return the same instance obj, so the call
obj.addX(3).addY(4)
will be equivalent to
obj.addY(4)
This is called method chaining.
The methods are implemented like this:
public SomeClass addX(int i) {
// ...
return this; // returns the same instance
}
public class Test1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Test1 abc = new Test1();
abc.add1(10, 20).sub1(40, 30).mul1(23, 12).div1(12, 4);
}
public Test1 add1(int a, int b)
{
int c = a + b;
System.out.println("Freaking Addition output : "+c);
return this;
}
public Test1 sub1(int a, int b)
{
int c = a - b;
System.out.println("Freaking subtraction output : "+c);
return this;
}
public Test1 mul1(int a, int b)
{
int c = a * b;
System.out.println("Freaking multiplication output : "+c);
return this;
}
public Test1 div1(int a, int b)
{
int c = a / b;
System.out.println("Freaking divison output : "+c);
return this;
}
}

Categories

Resources