I want to build Data main class with subclasses DataClass1(with own subclass Item) and DataClass2 (with own subclass Item1).
public class Data{
public List<DataClass1> dataClass1List = new ArrayList<DataClass1>();
public List<DataClass2> dataClass2List = new ArrayList<DataClass2>();
public class DataClass1{
public String name;
public List<Item> itemList = new ArrayList<Item>();
public class Item{
public String n1;
public String n2;
public String n3;
}
}
public class DataClass2{
public String name;
public List<Item1> item1List = new ArrayList<Item1>();
public class Item1{
public String n5;
public String n6;
}
}
}
When I want to fill main class Data I use this code:
Data data = new Data();
Item itm = new Item;
itm.n1="1";
itm.n2="2";
itm.n3="3";
data.dataClass1List.itemList.add(itm);
and same for dataClass2List
All sub classes must be public
Is there better way to declare and filling up my class Data
Thanks!!!
p.s. Data class and its sub classes contain only variables not methods!
You seem to be confusing some concepts here.
There are no subclasses in your code. DataClass1 and DataClass2 are inner classes of Data, Item is an inner class of DataClass1 and Item1 is an inner class of DataClass2.
There's no visible need for them to be inner classes, and you're best off avoiding inner classes until you're sure you need them and likely until you know Java a bit better.
With these as inner classes, your proposed usage of them will not work, as they're non-static inner classes, and can only be created within the context of an instance of the outer class.
With the class definitions as they are, a translation of your posted usage would be approximately
Data data = new Data();
DataClass1 dc1 = data.new DataClass1();
Item itm = dc1.new Item();
itm.n1="1";
itm.n2="2";
itm.n3="3";
dc1.itemList.add(itm);
data.dataClass1List.add(dc1);
But this is really quite bad (and it may contain mistakes - I have bothered trying to compile it). Having classes with only fields and no methods, and adding data in this way is not a very object-oriented approach at all.
As WirthLuce noted in a comment, you should change the names to represent something in your domain, and create methods to make them do something appropriate rather than just holding data that is manipulated from outside.
Some suggesions:
You should use getter and setter to access the different fields.
public class SomeClass {
private String name;
[...]
public void setName(String name) {this.name = name;}
public String getName() {return name;}
[...]
}
Since the Data classes are public, do they need to be inner class?
To fix this you would need to move the different public class to different files.
All internal lists could be made `final`.
public final List<Item> itemList = new ArrayList<Item>();
You could make a constructor for the class Item.
public class Item {
public Item(String n1,String n2,String n3) {
this.n1 = n1;
this.n2 = n2;
this.n3 = n3;
}
[...]
}
Related
I have studied data hiding in java theoretically but don't know what is happening inside. Every tutorial, states that unauthorized persons cant access the data of others.
Can anyone please give an example of what will happen without and with data hiding with two or three users programmatically?
Data Hiding is hiding internal data from outside users. This is achieved by making the attributes of your class private and not letting the objects of the class access it directly, instead we create getters and setters to access the private attributes.
Example:
//Without Data Hiding
public class Model{
public String name;
}
public class JavaApp{
public static void main(String args[]){
Model mObj = new Model();
mObj.name="abc"; // name = "abc"
}
}
//With Data Hiding
public class Model{
private String name; //private name
}
public class JavaApp{
public static void main(String args[]){
Model mObj = new Model();
mObj.name="abc"; // Error
}
}
So I have 3 classes, Lair, LairLocation & Minion. I created an ArrayList, which is supposed to store Minion objects, and this is an attribute of LairLocation. I'm supposed to create some objects to store in ArrayList, from the parent class Lair. Both LairLocation and Minion and sub-classes of Lair.
Whenever I try to create objects to store in ArrayList form my parent, I keep getting an error saying 'minion cannot be resolved' and telling me to create a local variable etc. Please help
LairLocation
'''
public class LairLocations extends Lair
{
public static ArrayList<Minion> minions = new ArrayList<Minion>();
}
'''
Lair
'''
public class Lair
{
public void createMinions()
{
minions.add("12", "Mine", "Me");//This is giving me the error
}
}
'''
Minion
'''
public class Minion extends Lair
{
private String id;
private String fName;
private String lName;
public Minion(String Id, String fName, String lName)
{
this.id = id;
this.fName = fName;
this.lName = lName;
}
}
'''
You're trying to access a field of a subclass from its parent class. This does not work this way.
You can only access fields of a parent class (if they're public or protected).
So, you either have to move your minions field to the parent class Lair (and make it non-static, by the way), or access this object via LairLocation class: LairLocation.minions() (if the field is supposed to be static).
Also, this line of code is incorrect: minions.add("12", "Mine", "Me");
The add() method accepts only one element.
It should probably be: minions.add(new Minion("12", "Mine", "Me"));
You have to call new Minion() to get a new minion.
minions.add( new Minion( "12", "Mine", "Me") );
I would like to know if i can get this to work:
public enum Items {
Weapon starterBow = new Weapon("Starter Bow", AttackSpeed.SLOW),
Weapon advancedBow = new Weapon("Advanced Bow", AttackSpeed.MEDIUM),
Weapon goldenBow = new Weapon("Golden Bow", AttackSpeed.FAST);
}
I want to access it like this:
Items.starterBow.getName()
(Weapons have a getName() Method)
This code snippet at the beginning is giving me errors, but is there any other way to list Objects like this? (Without creating a new class)
Thanks in advance!
enums syntactically act as regular classes, so you can have fields, methods and constructors.
The difference is that you specifiy the instances of the class during the enum declaration. These instances are created by the jvm and cannot be created in any other way.
This is probably what you are looking for:
public enum Items {
//Fields
String name;
AttackSpeed attackSpeed;
//constructor:
Items(String name, AttackSpeed attkSpd) {
this.name = name;
this.attackSpeed = attkSpd;
}
//methods:
public String getName() {
return name;
}
//listing the instances and calling the constructor:
StarterBow ("Starter Bow", AttackSpeed.SLOW),
AdvancedBow ("Advanced Bow", AttackSpeed.MEDIUM),
GoldenBow ("Golden Bow", AttackSpeed.FAST);
}
I am writing a program with different classes and there there is a collection class which will store only the sub-classes of the superclass.
Okay, so i have an Order super class that stores quantity. The code snippet is like this:
abstract class Order { //superclass
private int quantity; //instance variables
public Items(int quantity) { //constructor
this.quantity = quantity;
}
public int getQuantity() { // instance method
return quantity;
}
public abstract double totalPrice();
Then i have sub-classes of the order class. The sub-classes are below.
class Coffee extends Order { //subclass
private String size; //instance variables
public Coffee (int quantity, String size) { //constructor
super(quantity);
this.size = size;
} //... some other methods
} // end of Coffee class
class Donuts extends Order { //sub-class
private double price; //instance variables
private String flavour;
public Donuts(int quantity, double price, String flavour) { //constructor
super(quantity);
this.price = price;
this.flavour = flavour;
} //...some other methods
} //end of donut class
class Pop extends Order {
private String size;
private String brand;
public Pop(int quantity, String size, String brand) {
super(quantity);
this.size = size;
this.brand = brand;
} //...again there are some other methods
} //end of pop sub-class
Now this is where i need help. I have written a collection class that contains ArrayList<>. The code snippet is this:
class OrderList {
private ArrayList<Order> list;
public OrderList() {
list = new ArrayList<Order>();
}
What i want to do in the collection class is to have instance methods that ensure that only sub-classes are only added to my collection class.*
What i have tried so far is this (which makes me a complete fool, i know that).
public void add(Coffee cof) {
list.add(cof);
}
public void add(Donut don) { // i know we cant have methods with the same name
list.add(don);
}
public void add(Sandwich sand) {
list.add(sand);
}
public void add(Pop p) {
list.add(p);
}
SO community can you please give me some hints on my problem.
You are getting your abstractions wrong. A Product .. isn't an Order.
A Product is simply a Product. It has some "identity", and probably different "flavors". But when you think about it, initially, it is not an order. An order comes into existence when a customer selects various products, puts them into some shopping card ... and hits the "order" button.
Just think how things are "in the real" world. And that is what should guide the model that you build.
Meaning: your Products should not subclass Order. Instead, you could be doing something like:
public abstract class ShopItem {
// that contains those things that all products in the shop have in common, like
public abstract double getPrice();
...
and then all your Products extend that class. It might be even more useful to avoid inheritance here completely, and turn ShopItem into an interface (that would depend if you really find good reasons to use an abstract class; in order to define common behavior of ShopItems).
Next:
public class ProductOrder {
private final ShopItem orderedItem ...
private final int quantity ...
And to bring things together:
public final class Order {
private final List<ProductOrder> allItemsOfAnOrder ...
Your method signature will be:
public void add(Order order){
...
}
because an Order can hold reference to any of its subtypes.
I don't really see the need for your own OrderList. Since Order is an abstract class, you can only add instances of non-abstract child classes to any List<Order> that you declare.
Also, instead of
class OrderList {
private ArrayList<Order> list;
public OrderList() {
list = new ArrayList<Order>();
}
}
you can also use
class OrderList extends ArrayList<Order> {
public OrderList() {
super();
}
}
and then simply use the add(Order element) that you inherited from your parent class.
But then again, it might be more convenient to just declare an ArrayList<Order> wherever you intended to use your OrderList, as long as you don't add any new methods (that are not given by a regular List) to justify having an extra class.
I'm currently having difficulty getting my new subclass to compile:
public class CompilationAlbum extends Album {
private String seriesOfAlbums;
public CompilationAlbum(String seriesOfAlbums) {
this.seriesOfAlbums = seriesOfAlbums;
albumType = "Compilation";
}
}
Can anyone point out what I'm doing wrong? The fault seems to lie with the constructor, but I can't see why that should cause an error. The error message also reads "actual and formal argument lists differ in length."
EDIT: The Album class, minus methods, looks like this:
import java.util.ArrayList;
public class Album {
private String name;
private ArrayList<Track> trackList;
private int length;
private int fileSize;
private double averageRating;
private String albumType;
public Album(String name){
this.name = name;
trackList = new ArrayList<Track>();
}
If you don't explicitly call a constructor of the superclass in the first line of the subclass constructor, a call to super() is inserted by the compiler. Since Album doesn't have a no-argument constructor, compilation fails because the inserted call to super() isn't valid.
There are two ways to resolve this - either call the existing superclass constructor with some String argument (you'd have to decide what makes sense for your particular use case), or add a no-argument constructor to the superclass (again, the behavior of this constructor will depend on what you're actually trying to do).
Here's an approach that might make sense:
public class CompilationAlbum extends Album {
private String seriesOfAlbums;
public CompilationAlbum(String name, String seriesOfAlbums) {
super(name);
this.seriesOfAlbums = seriesOfAlbums;
albumType = "Compilation";
}
}
Without seeing the source code for Album, I'm guessing that it does not have a default constructor.
You wrote this:
public class CompilationAlbum extends Album {
private String seriesOfAlbums;
public CompilationAlbum(String seriesOfAlbums) {
this.seriesOfAlbums = seriesOfAlbums;
albumType = "Compilation";
}
}
You want this:
public class CompilationAlbum extends Album {
private String seriesOfAlbums;
public CompilationAlbum(String seriesOfAlbums) {
super(seriesOfAlbums);
this.seriesOfAlbums = seriesOfAlbums;
albumType = "Compilation";
}
}
Now that I see the Album class, your problem is private members. Make those protected so child classes can get at them, too.