ArrayList Of Interface - Does It Rip Away Data From Child Classes?
Nov 29, 2014
If I lets say have an interface Animal, and I create a lot of classes with a different animal name that implement the interface Animal. Then I create an ArrayList of Animal. Then I would put in lets say Dog class into the ArrayList, which has custom methods and data that the Animal Interface doesn't have, is this data ripped away except for the methods that are put in the Animal interface? So if I would cast the Animal back to Dog, would it retain all the data that existed before it was placed in the ArrayList?
View Replies
ADVERTISEMENT
Jan 25, 2014
I have been working on a simple problem, but I am stuck. I am trying to learn parent and child classes and how they work. The program in broken into three classes; the DemoBook class that runs the various methods, the Book class that gathers information and displays it, and finally a child class of Book (called TextBook) that just gets one piece of data and then is suppossed to return that data back to Book. However, this is not working and I know I am missing something; I believe it has to do with Set and Get methods, but I am confused with how these work.
Java Code:
public class DemoBook
{
public static void main (String[] args)
{
Book aBook = new Book();
Textbook aText = new Textbook();
[Code] .....
View Replies
View Related
Jun 7, 2013
I found the following inheritance and encapsulation issue . Suppose you have a parent class with a non-static protected attribute.
package package1;
public class Parent{
protected int a = 10; // this is the non-static protected attribute in question
public static void main(String args[]){
// whatever logic
}// end Parent class
}// end main()
Now suppose you have a child class in another package and you have imported in the parent class.
package package2;
import package1.Parent;
public class Child extends Parent{
public static void main(String[] args){
Parent p = new Parent();
Child c = new Child();
System.out.println(p.a); //should print out 10 BUT DOES NOT
System.out.println(c.a); //should print out 10
}// end main()
}// end Child class
My observation is that p.a produces an error even though, to the best of my knowledge, it should not. I believe the statement "System.out.println(p.a);" should print out a 10.
Am I misunderstanding something about inheritance and encapsulation?
View Replies
View Related
Feb 13, 2014
I have the following code that will make linked list and order its elements using self referential objects. but i have the following error:
incompatible types
required: ListNode<T#2>
found: ListNode<T#1>
where T#1,T#2 are type-variables:
T#1 extends Comparable declared in method <T#1>insertInOrder(T#1)
T#2 extends Comparable declared in class OrderedList
import java.util.*;
public class ListNode<T> {
ListNode<T> nextNode;
T data;
public ListNode(T item)
{
this(item, null);
[code]...
View Replies
View Related
Jun 4, 2014
why don't I define my methods in a class, rather than going a level up and declaring it first in an abstract class/interface? If the point is to have different implementations for different needs, then we have the option to override the methods.
View Replies
View Related
Oct 20, 2014
I am new to Java, and last week had an assignment to create a shopping list. I made it so that I have one class use a ProductData class to load an array of objects (description, price, priority). This week I need to take that program and change it so that it includes an Interface and Abstract Class. I need to also split one class up into at least 2 others.
I am having trouble getting my thoughts together and figuring out what to put in the interface and what to put in the abstract class. I'm thinking that it might be best to split up the ProductData class up into 3 different classes: description, price, and priority. Then have an interface with a print method. Each of those 3 classes will implement the interface.
As for the abstract class, have the price and priority extend the abstract class. The abstract class will be at the same level as the interface and contain the set and get methods. Right now they are of 2 different data types: int, double. Should I make both of them Double, and then use a method to change the priority to an int?
Should price and priority inherit from description, or should they all be at the same level? I am thinking that they should be at the same level because they all describe the item in the array.
My most confusing part is that I have no clue at all on how I can load that array when each object is split up in a different class. My professor went over ArayLists last week, and we can now use them if we want, but the assignment doesn't explicitly say that we should change it to an Array List. Where does the constructor for the ProductData() go? Do I split it up into 3 different constructors?
View Replies
View Related
Jan 8, 2014
I am writing a game in Java for Android (although my question isn't Android or Game Dev specific).
I have a SceneManager class and a Scene interface and then various other classes that implement the Scene interface (Code at the end of this post).
Basically, in my MainGame class (which also implements the Scene Interface for Touch Event capturing purposes) I hold the bulk of my game code. Methods in this class are then called from my Level classes. (most of these are needed in all levels so it makes sense to hold them here and call them from the levels to eliminate unnecessary code duplication)
So, I have Level1, Level2......... Level20 classes which all implement Scene.
Now, the problem comes because in only 2 of my Levels something can happen (that can't in the other 18) and I need to run a response method in these 2 levels (the method isn't exactly the same, the response to this event happening is different for both levels).
To run common methods from my classes, I use my Scene Manager like this:
SceneManager.getInstance().getCurrentScene().updateLogic();
SceneManager.getInstance().getCurrentScene().render();
(The above is from my gameloop) - So it will run the updateLogic(); and render(); methods from whichever is the current scene (Level).
Scene is changed like so:
SceneManager.getInstance().setCurrentScene(LevelX);
This works great as all Level's have an updateLogic(); and render(); method.
So from my mainGame class, I am doing something like : (pseudo code)
public void checkIfSomethingHappened(){
if (something happens){
if (currentLevel==5){
Level5.response();}
[Code]....
The above would be called from my 2 level classes. So something like:
MainGame.checkIfSomethingHappened(); //Called in addition to the normal methods that make up that level
I don't really want to have this (second) 'if' statement here in the middle of my performance critical game loop.
What I'm after is something like this:
if (something happens){
SceneManager.getInstance().getCurrentScene().response();
}
However, this would require me to put stubs in the other 18 classes.
I'm thinking there must be a way to do this as the SceneManager already knows the current scene so it seems a waste checking it again via an if (or switch) statement. What is the best way to do this without having to put stubs into classes that don't require this method?
View Replies
View Related
Dec 16, 2014
Can i type cast a interface to ArrayList? suppose there is a interface Named Node.
public interface Node
{
public static final short ELEMENT_NODE=1;
......
.....
}
i want to typecast this interface to ArrayList and fetch all the value.You can use hashtable object class etc.my main moto is to take a value in ArrayList and traverse it.
View Replies
View Related
Apr 14, 2014
I am new a creating GUIs and am not quite sure how to correctly make one. I have done the inheritance parts, and created two extra appliances: a washer and dryer. Now Creating the GUI ....
Here are the instructions to my project.
Introduction to GUIs (+ some inheritance)
For this assignment, you are going to create a user interface that interacts with the setters and getters of some classes that you will create.
First, create an abstract class called Appliance. This abstract class should have two attributes (dealing with household appliances) and two abstract methods called turnOn() and turnOff(). These methods should return void.
Then, create two subclasses of Appliance that represent household appliances (like a Refrigerator or Stove ((don't use those!))). These subclasses should have two attributes that are specific to the various appliance. Each subclass should implement the turnOn() and turnOff() methods. These methods should print to the command line some information about the appliance as it turns on and off.
Now, the fun part! Create a GUI interface!
Your window should have two panels: one for each appliance subclass. Each panel should have 4 textboxes (with appropriate labels) to receive/display information that correspond to the 4 attributes (2 from Appliance and 2 from the subclass) for each subclass.You also need 2 buttons on each panel: A Get button and a Set button.
When the Get button is pressed, the text boxes should be filled with the information from the instantiated object of the appropriate subclass. When the Set button is pressed, the object should then contain the information contained that the user has altered.
In your main method, you should create an object of each subclass, and prefill it with information (either using the constructor or the setters), then display your GUI. You should now be able to get and set the information for your objects from the GUI.
At least one of your attributes for each subclass should be numeric
Note that you will need to handle incorrectly formatted input (You can use exception handling to do this if you want to. Wrapper classes also will work)
If there is text in the boxes when the "Get" button is pressed, it should be overwritten by what is in the object. Remember that these two panels should both be on screen at the same time.
You don't need 2 different windows, one window: 2 panels.
View Replies
View Related
Oct 6, 2014
I have written several simple data classes that I serialized manually by converting to text. At this point I need to serialize a more complex data structure. which will include lists of the simpler elements. Can serialize store and reconstitute this type of structure automatically or do I need to do this one manually as well? Consider the pseudocode below for a clarification of my question;
Java Code:
Class Hops{
String Name;
float Alpha Acid;
float Beta Acid;
};
Class Malt{
String Name;
float extract;
};
Class Recipie{
String Name;
CList HopList;
CList MaltList;
};
CList RecipieList; mh_sh_highlight_all('java');
I read the article on Serialization presented at tutorial point, but the example only showed a simple class, not lists of class members. What I want to do is serialize RecipieList, which consists of a CList of Recipies, which in turn consist of CLists of various ingredients.
View Replies
View Related
Oct 25, 2014
I have to make a retail item class that has description, price and quantity. I then have to make a CashRegister class that calculates subtotal, tax, total and displays it (toString). I also have to make a driver class to call the methods from main. I have no clue what I am doing and what I have done does not work. I am trying to make it sort of like a cart, in the CashRegister it should ask the user to enter the description, quantity purchased and the price. Then it would send that to the arraylist of retailitem. I am having trouble using those items in my other methods and then do not know how to call those in the driver class.. So here are my classes:
public class RetailItem {
private String description;
private int quantity;
private double price;
public RetailItem(){
description = "";
quantity = 0;
[Code] ....
View Replies
View Related
Oct 25, 2014
Alright.. So I have to make a retail item class that has description, price and quantity. I then have to make a CashRegister class that calculates subtotal, tax, total and displays it (toString). I also have to make a driver class to call the methods from main. I have no clue what I am doing and what I have done does not work. I am trying to make it sort of like a cart, in the CashRegister it should ask the user to enter the description, quantity purchased and the price. Then it would send that to the arraylist of retailitem. I am having trouble using those items in my other methods and then do not know how to call those in the driver class...
So here are my classes: [URL] ....
View Replies
View Related
May 8, 2015
I have seen many ways of describing what objects are, one being that objects are a user-defined datatype. However, if objects are datatypes, then what does that make classes? To me, it seems as though classes should be the "types" of data defined by the programmer, and objects should be the specific "values" of that user defined data type. As an example, an integer would be a class, while 1 would be a "value" of that class, i.e. an object. From this point of view, I don't see why a specific number would be a data type... Therefore, why do we say that objects are user defined data types rather than classes?
View Replies
View Related
Jan 22, 2014
What I'm doing about it: googling the shit out of my problems, consulting you fine readers, consulting my friends, and yesterday I signed up for Lynda.com. I'm hoping 30hrs+ or so of watching, rewatching, and analyzing the example code will catch me up before I get too behind in CS302
** Assignment Prompt **
Integer types are very convenient, but their limited width and precision makes them unsuitable for some applications where precision is more important than speed. Develop a class VeryLargeInteger that can handle arbitrary long integer numbers (both negative and positive) and the basic arith- metic operations (addition, subtraction, multiplication, division, and remainder).
Hint: The number could be represented as string, the sign could be represented either as boolean or as part of the string.
Note: Implementations of addition/subtraction through repeated use of a constant incremen- t/decrement will not be accepted. Implementations of multiplication and division that rely only on addition and subtraction will not be accepted.
I know I'm going to have to create a separate tester to call on the VeryLargeInteger class and it's math methods. For the new data type, should I convert the integer/string into an array in order to handle the large length of the number? I know he wants us to use recursion for the math methods. My gut tells me addition and subtraction will be slightly easier than multiplication and division. I know I'll have to reference the other methods for division. We aren't allowed to use the BigInteger class.
How I should construct any of the methods.
Java Code:
import java.util.ArrayList;
/**
∗ VeryLargeInteger (VLI) is a class for arbitrary precision integer computation
*/
public class VeryLargeInteger {
private int[] num1;
private int[] num2;
private int[] num3;
[code]....
View Replies
View Related
Nov 12, 2014
I have a problem with this ascii animation program I am working on. I declared a method inside of my class AsciiAnimation extends JFrame implements ActionListener, called
package AsciiAnimation;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
public class AsciiAnimation extends JFrame implements ActionListener{
int currentFrame = 0;
ArrayList<String> frameList = new ArrayList<String>();
[Code] ....
Basically I just am trying to figure out how java works with me accessing those 2 data members, currentFrame and frameList inside of my first class ALL in the same package.
View Replies
View Related
May 24, 2015
My code is like follows. I want add the lines of data from text file to arraylist.After add the lines to array list,i want to get the interesection between the lines of data. But I could not get the intersection and it returns empty. My sample data from specific line in text file as follows,
line 1 data:5 1 1 1 2 1 3 1 1
line 2 data:5 4 4 5 7 10 3 2 1
try {
File f1 = new File("C:/users/User1/Desktop/Datasets/Dataset.txt");
String filename = f1.getAbsolutePath();
FileReader reader = new FileReader(filename);
BufferedReader br1 = new BufferedReader(reader);
[Code] .....
View Replies
View Related
Dec 4, 2014
I have created this project and want to be able to add new members to my members arraylist, store the input in a .txt file and load the new members after closing and opening the program.
[URL] .....
View Replies
View Related
Nov 16, 2014
I have declared an array list that will store data type of 1 Character and 2 integer. The data that will be store in this list is
1. A = {0 3}
2. B = {0 5}
3. C = {0 3}
4. D = {0 3}
5. E = {0 5}
6. F = {0 6}
Now here the alphabets are routers and integers are there con1 and con2 respectively. I have a set of router={ A,B,C,D,E,F}.
Step 1:I have to subtract con1 from con2 i.e. (3-0) of all the routers and
Step 2: then put the router having largest value in new set 1 and
Step 3: then this router will be subtract from the router set.
Step 4:then again I have to repeat the step 1 until the value of routers become <= 1.
Now what I did is I defined 3 arrays first is String array that stores names of routers, 2nd array that stores the first value and 3rd array that stores the second value. I can find the largest value but how to store the name of router against the largest value in the set.
View Replies
View Related
May 23, 2014
Java Code:
public void draw(ArrayList<int[]> good,ArrayList<int[]> bad){
drawing = true;
goodToDraw=good;
badToDraw=bad;
System.out.println("Canvase/draw: Calling paint with a size of "+goodToDraw.size());
middleMan();
[code]....
What this does is two ArrayList are sent to the draw function.one called good and the other bad. Right now I am only working on good. What is suppose to happen is paint takes all the good coordinates and paints them but I seem to loose the arrayList size when repaint is called. You can see in the picture below of my console that it starts of with 20. Then because I was wondering if the scope was to short i called middleman to make sure that it held its size outside of the first function. Then finally it calls paint and tells me the array is empty. To simplefy..Why does my arraylist size go to zero when I call repaint?
View Replies
View Related
Dec 4, 2014
I have created this project and want to be able to add new members to my members arraylist, store the input in a .txt file and load the new members after closing and opening the program.
[URL] ....
View Replies
View Related
Feb 18, 2015
I am trying to write a program that will take any comma separated data set and return the values in an arraylist without any commas. Like if I input "hello, world, program, java" it would output an arraylist [hello,world,program,java].
public void run(){
String line = readLine("Enter a CSV-formatted line of data: ");
int lowerBound = 0;
String entry = new String("");
ArrayList<String> string = new ArrayList<String>();
[Code] .....
View Replies
View Related
Aug 25, 2014
I would like to create an ArrayList from data types stored in a text file.The ArrayList would be multidimensional with two data types; int, String.
Example text file could be:
4 cahiers grand format
3 stylots bic bleu
5 gommes
I find it very difficult for multiple data types i don't see how its possible.
View Replies
View Related
Sep 1, 2014
I am trying to remove the duplicate elements from ArrayList using .contains() if elements are primitive datatype it works but user-defined datatype does not work.
public class UserBean {
String name;
String address;
public String getName() {
return name;
[code]....
View Replies
View Related
Oct 25, 2014
I managed to retrieve data, and set data in my own ways in which I like. But my problem is, if the file does not contain anything (fully empty), when I try to use my
set("", "");
method, it only sets the last one that is called.
Example:
set("section1", "section1Item");
set("section2", "section2Item");
set("section3", "section3Item");
Only section3 would get set, and not the others.
Otherwise, if the file contained a section already, then each section (section1, section2, section3) would get set.
Here's how I set the data to the file:
public static void set(String section, String data) {
files.openFileWriter();
files.file.delete();
reCreateFile();
String beforeItem = section + ":" + files.dataList.get(section);
[code]....
And here is how a retrieve the data and set them to my arraylist/hashmap:
public void getData() {
String line = null;
openFileReader();
StringBuffer sb = new StringBuffer();
[code]....
View Replies
View Related
Jun 9, 2014
Below code gets printed as output?
public interface I1 {
public void method();
}
public interface I2 {
public void method();
}
public interface I3 extends I2, I1 {
[Code] ....
View Replies
View Related
Jan 1, 2015
I have the following objects:
User Object:
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(unique = true, nullable = false)
private int id;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "user", cascade = CascadeType.ALL)
private List<UserReason> userReasons;
....
Code :
public List<UserReason> getUserReasons() {
return userReasons;
}
public void setUserReasons(List<UserReason> userReasons) {
this.userReasons = userReasons;
}
public UserReason addUserReason(UserReason userReason) {
if (userReasons == null) {
userReasons = new ArrayList<UserReason>();
[Code] ....
I want to be able to add userReason to the list, and that Hibernate will automatically update the reference between the parent & child object.
When using the above code, when trying to start the server, i'm getting the error message:
Repeated column in mapping for entity: com.commit.safebeyond.model.UserReason column: userId (should be mapped with insert="false" update="false")
Please notice that i mapped the userId in UserReasonPK with insertable = false, updatable = false.
If i change it, and add this on the User property in UserReason object, server is up, but when trying to insert new User I'm getting the following error:
Hibernate: insert into UserReasons (reasonId, userId) values (?, ?)
WARN 2015-01-01 13:25:17,488 [http-nio-8080-exec-2] org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 1452, SQLState: 23000
ERROR 2015-01-01 13:25:17,488 [http-nio-8080-exec-2] org.hibernate.engine.jdbc.spi.SqlExceptionHelper - Cannot add or update a child row: a foreign key constraint fails (`SafeBeyond`.`UserReasons`, CONSTRAINT `FK_UserReasons_Users` FOREIGN KEY (`userId`) REFERENCES `Users` (`id`))
[Code] ....
View Replies
View Related