first year CS exam, need guidense [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
i have my exams tomorrow in java. It is focus on encapsulation, cohesion, coupling, inheritance and interface. I made a project of seven classes, speaker and headset class inherits from sound class and product class and DjMixer implements just from product.The main class is still empty. I need to know if I'm making any crucial mistakes in my code design.
public interface Product
{
double getPrice();
void setPrice(double price);
String getId();
void setId(String Id);
String getPlace();
void setPlace(String place);
}
public abstract class Sound
{
public abstract void setDesibel(int desibel);
public abstract int getDesibel();
public void amp() {
System.out.println("Recomended amplifier effect is 40-250 watts");
}
}
public class Speaker extends Sound implements Product
{
double price;
String id;
String place;
int desibel;
/**Price in Norwegain Kroner */
public double getPrice(){
return price;
}
/**Price is set in Norwegain Kroner */
public void setPrice(double price){
this.price = price;
}
/**Location of the product*/
public String getPlace(){
return place;
}
public void setPlace(String place){
this.place = place;
}
/**The products European Article Number*/
public String getId(){
return id;
}
/**type in the European Article Number under the barcode*/
public void setId(String serialNum){
id = serialNum;
}
//Constructor
public Speaker(double price, String location, String serialNum) {
super.amp();
this.price = price;
place = location;
id = serialNum;
}
public int getDesibel() {
return this.desibel;
}
public void setDesibel(int desibel) {
this.desibel = desibel;
}
}
public class Headset extends Sound implements Product
{
double price;
String place;
String id;
int desibel;
boolean wireless = true;
/**Price is in Norwegain Kroner */
public double getPrice(){
return price;
}
/**Price is set in Norwegain Kroner */
public void setPrice(double price){
this.price = price;
}
/**Location of the product*/
public String getPlace(){
return place;
}
/**Set location where item is stored */
public void setPlace(String location){
place = location;
}
/**The products European Article Number*/
public String getId(){
return id;
}
/**type in the European Article Number under the barcode*/
public void setId(String serialNum){
id = serialNum;
}
//Constructor
public Headset(double price, String location, String serialNum) {
super();
this.price = price;
place = location;
id = serialNum;
}
public void setDesibel(int desibel) {
this.desibel = desibel;
}
public int getDesibel() {
return this.desibel;
}
}
public class DjMixer implements Product
{
double price;
String id;
String place = "Storage room, shelf 3";
/**Price in Norwegain Kroner */
public double getPrice(){
return price;
}
/**Price is set in Norwegain Kroner */
public void setPrice(double price){
this.price = price;
}
/**Mixing tables is stored on shelf 3, if moved please set new place */
public String getPlace(){
return place;
}
/**Set new place for mixing table if moved */
public void setPlace(String location){
place = location;
}
/**The products European Article Number*/
public String getId(){
return id;
}
/**type in the European Article Number under the barcode*/
public void setId(String serialNum){
id = serialNum;
}
public DjMixer(double price, String serialNum){
this.price = price;
id = serialNum;
}
}

It would be a good idea to declare any variable that can be accessed via a "get" method as private. Also, you put "desibel" instead of "decibel" in some of your methods. If your teacher has taught you the final keyword, the wireless boolean seems like it should be declared as such.

Related

Add Part object to observableArrayList<Part> associatedParts in the Product class in Java

I am working on my class assignment and I am stuck.
I have two classes: Part, which is abstract and has InHouse and Outsourced classes that extend Part. Then I have Product, which oddly has an observableArrayList of parts called associatedParts.
I am working on my AddProductController, trying to make a call to the method in the Product class addAssociatedPart(). My problem is the compiler doesn't find the method in Part. If I cast to an InHouse, it doesn't find the method in InHouse, and so on. I can't use a static method, because the method addAssociatedPart() is supposed to be non-static per the UML design. So, I can't tell it explicitly to find it in Product.addAssociatedPart(), because it tells me I can't reference a non-static etc.
Here's the code snippets starting with the Product class.
public class Product {
private ObservableList<Part> associatedParts = FXCollections.observableArrayList();
private int id;
private String name;
private double price;
private int stock;
private int min;
private int max;
public void addAssociatedPart(Part part) {
getAllAssociatedParts().add(part);
}
public ObservableList<Part> getAllAssociatedParts() {
return this.associatedParts;
}
And then the AddProductScreenController class:
public class AddProductScreenController implements Initializable {
#FXML
public void onAddProductAddPart(ActionEvent event) {
// this is triggered when the Add button is clicked
Part selectedItem = addProductTableViewAll.getSelectionModel().getSelectedItem();
selectedItem.addAssociatedPart(); // can't find method
Product.selectedItem.addAssociatedPart(); // can't find variable selectedItem (obviously bad formatting)
selectedItem.Product.addAssociatedPart(); // can't find variable Product (again bad formatting)
addAssociatedPart(selectedItem); // can't find method addAssociatedPart()
Product.addAssociatedPart(selectedItem); // non-static method, can't be referenced from a static context
InHouse newPart = new InHouse(1, "test", 1.99, 1, 1, 1, 101);
addAssociatedPart(newPart); // can't find method
Product.addAssociatedPart(newPart); // non-static method
newPart.addAssociatedPart(); // can't find method
addProductTableViewPartial.setItems(associatedParts);
}
}
The part code as requested:
public abstract class Part {
private int id;
private String name;
private double price;
private int stock;
private int min;
private int max;
public ObservableList<Part> allParts = FXCollections.observableArrayList();
public Part(int id, String name, double price, int stock, int min, int max) {
this.id = id;
this.name = name;
this.price = price;
this.stock = stock;
this.min = min;
this.max = max;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return this.id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setPrice(double price) {
this.price = price;
}
public double getPrice() {
return this.price;
}
public void setStock(int stock) {
this.stock = stock;
}
public int getStock() {
return this.stock;
}
public void setMin(int min) {
this.min = min;
}
public int getMin() {
return this.min;
}
public void setMax(int max) {
this.max = max;
}
public int getMax() {
return this.max;
}
}
This is InHouse
package model;
public class InHouse extends Part {
private int machineId;
public InHouse(int id, String name, double price, int stock, int min, int max, int machineId) {
super(id, name, price, stock, min, max);
this.machineId = machineId;
}
public void setMachineId(int machineId) {
this.machineId = machineId;
}
public int getMachineId() {
return this.machineId;
}
}
And then Outsourced:
package model;
public class Outsourced extends Part {
private String companyName;
public Outsourced(int id, String name, double price, int stock, int min, int max, String companyName) {
super(id, name, price, stock, min, max);
this.companyName = companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getCompanyName() {
return this.companyName;
}
}
If there is a particular part of Java you feel I need to brush up on to understand this, I am wide open to that. I want to understand the issue, not just get a fix. I'm not even looking for the answer, just a point in the direction of what the problem is.
Update
#Le and #Jackson pointed me in the right direction with their comments on the response he provided. I need to have a product first:
Product product = new Product(1, "test", 1.99, 1, 1, 1);
product.addAssociatedPart(selectedItem);
I was trying to explain you association of your various classes in comments but thought I would use visual help. I have simplified your scenario into a classic OOP problem.
public class Product {
public void addAssociatedPart(Part part) {
// some stuff
}
}
public abstract class Part {
}
public class InHouse extends Part {
}
public class Outsourced extends Part {
}
public class Assembly {
public static void main(String[] args) {
Product car = new Product();
Part seat = new InHouse();
Part engine = new Outsourced();
Part window = new InHouse();
car.addAssociatedPart(seat);
car.addAssociatedPart(engine);
car.addAssociatedPart(window);
}
}
I do not have any method in my Part or its sub-classes to add themselves to some Product. Was this you trying to achieve?
I am working on my AddProductController, trying to make a call to the
method in the Product class addAssociatedPart().
My problem is the compiler doesn't find the method in Part.
Why should it? Is Part a child of Product? Otherwise, you are calling a Product Method using a Part instance.
To use the methods of Inhouse and Oursourced for parts, you can do something like this
if (selectedItem instanceof InHouse){
Inhouse inhouse = (Inhouse)selectedItem;
//do what you need with inhouse methods
}else{
Outsourced outsourced = (Outsourced)selectedItem;
//do what you need with oursourced method
}
You are confused with static and non static method. You need a Product instance to access AddAssociatedPart(). Visualize your class in class diagram.
public void onAddProductAddPart(ActionEvent event) {
// this is triggered when the Add button is clicked
Part selectedItem = addProductTableViewAll.getSelectionModel().getSelectedItem();
selectedItem.addAssociatedPart(); // addAssociatedPart() is method of Product, not Part
Product.selectedItem.addAssociatedPart(); // Product class has no static member selectedItem
selectedItem.Product.addAssociatedPart(); // syntax error
addAssociatedPart(selectedItem); // addAssociatedPart() is not method of AddProcutController
Product.addAssociatedPart(selectedItem); // if you reference the method start with a class, the method is expected to be a static method. addAssociatedPart() is not a static method, call it with a product instance
InHouse newPart = new InHouse(1, "test", 1.99, 1, 1, 1, 101);
addAssociatedPart(newPart); // addAssociatedPart() is not part of AddProductController
Product.addAssociatedPart(newPart); // dont reference non-static method with a class name
newPart.addAssociatedPart(); // addAssociatedPart() is not part of Part
addProductTableViewPartial.setItems(associatedParts);
}

Pass values to parameters

when i trying to do this i got the problem said
Constructor Product in class Product cannot be applied to given types;
required: java.lang.String,int,double; found: java.lang.String;
reason: actual and formal arguments lists differ in length
And i have 2 classes:
import java.text.*
public class Product {
private String name;
private int stock;
private double price;
public Product(String name, int stock, double price) {
this.name = name;
this.stock = stock;
this.price = price;
}
public double sell(int n) {
stock = n;
return stock;
}
public void restock(int n) {
}
#Override
public String toString() {
return stock + name + "at $"+price;
}
}
public class Store {
public static void main(String[] args) {
new Store().use();
}
private Product product;
private Product cashRegister;
public Store() {
product = new Product("Sticky tape");
cashRegister = new Product("Cash register");
}
public void use() {
}
private void sell() {
}
private void restock() {
}
private void viewStock() {
}
private void viewCash() {
}
private void help() {
System.out.println("Menu options");
System.out.println("s = sell");
System.out.println("r = restock");
System.out.println("v = view stock");
System.out.println("c = view cash");
System.out.println("x = exit");
}
}
I understand that i have to declare for Product constructor. But i think i have done it. If anyone know where i got wrong please explain. Thank you!
you do not have constructor with one param, so you can not using this form
product = new Product("Sticky tape");
decare one more constructor with one param or fill all param
product = new Product("Sticky tape", 10, 20.0);
You need to:
overload the constructor
public Product(String name){...}
or create instances of Product using the right and only one constructor uor have:
public Product(String name, int stock, double price)
if you overload then something like this should happen
public Product(String name){
this(name, 0, 0.0);
}
so you call a constructor from the other constructor
This is the time to learn constructor overloading. Overloading comes from OOP.
You can use Overloading to methods and constructors. Overloading means for a same method name you can implement that method
several time with different parameters(number of parameters)
. Actualy not only that,
you can use different data types for parameter.
also can change order of parameter.
keep remember method name must be same.
For the constructor also same thing. If you use for constructor you can add parameters like:
//constructor with one parameter
public Product(String name) {
this.name = name;
this.stock = 0;//or whatever your default value
this.price = 0;//or whatever your default value
}
//constructor with two parameter
public Product(String name, , int stock) {
this.name = name;
this.stock = stock;
this.price = 0;//or whatever your default value
}
public Product(String name, int stock, double price) {
this.name = name;
this.stock = stock;
this.price = price;
}
Like that you can add as many as you want.
Or you can use one constructor and pass argument to match with the implementation of the constructor when creating object. Like below:
product = new Product("Sticky tape", 0, 0);
this is not complete description you can read this to learn more
You have no constructor In Product class that takes single String argument. Create it like so:
public Product(String name) {
this.name = name;
}
In import statement you forgot semicolon:
import java.text.*;
your program is having 3 coding error which include
you forgot the " ; " after " import java.text.* " actually it is not required in your code, you can remove it, nothing will change.
you cannot make class Product as public , because you've made "Store" as your Primary class having main method.So remove public keyword from the Product class.
You didn't create a parameterized constructor
which should be like
public Product(String name){ this.name = name;}
in your product class.
your code will be like after correcting
class Product {
private String name;
private int stock;
private double price;
public Product(String name, int stock, double price) {
this.name = name;
this.stock = stock;
this.price = price;
}
public Product(String name) {
this.name = name;
}
public double sell(int n) {
stock = n;
return stock;
}
public void restock(int n) {
}
#Override
public String toString() {
return stock + name + "at $"+price;
}
}
public class Store {
public static void main(String[] args) {
Store s = new Store();
System.out.println(s.product);
System.out.println(s.cashRegister);
}
private Product product;
private Product cashRegister;
public Store() {
product = new Product("Sticky tape");
cashRegister = new Product("Cash register");
}
}
The errors are in these lines of code:
product = new Product("Sticky tape");
cashRegister = new Product("Cash register");
The Product constructor defined expects:
public Product(String name, int stock, double price)

Why can't I accesses the properties of an object stored in a element of a ArrayList?

I have two packages lets give them the name package 1 and package 2.
Class A and Class B is in package1. Class A contains an ArrayList called PTable. Class B contains a function called query() that filters through PTable,in Class A, based on a certain conditions and returns an ArrayList called result that contains all the elements from PTable that meet that condition.
I now have package2 that contains Class C. Class C imports Class B from package 1; Class C is a subclass of HttpServlet. I create an object of Class B in class C and initializer it.
I then call the function query() and assign it to a variable called results. When I try and get the properties of an element at a certain index, I can't see the properties of the original objects stored in the ArrayList PTable.[This is what appears when I try and access the properties of the objects. My aim is to see the second image ][1]
Nice to ask questions but first spend sometime studying Java. Read a book or online and you will learn about casting very quickly. Also about classes, super classes etc
Your storing the objects in a variable of type Element (your results array list).
Cast the object back to the type it belongs too and then you will see the variables.
Code design note : storing different types of classesin the same array list is legal and possible but bug prone. Try to avoid it. If you change the order of storing variables into the list, you need to change all the access code too. Anyway happy learning.
There are free online Java tutorials study them -> https://www.google.co.in/search?q=java+tutorial+beginner
Sample class, in the main method try to get the object at position 1 and cast it to a Person :
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
super();
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Car {
private String manufacturer;
private String model;
private double price;
private int yearOfMfr;
private Date dateBought;
private String licenceNumber;
public Car() {
super();
}
public Car(String manufacturer, String model, double price, int yearOfMfr, Date dateBought, String licenceNumber) {
super();
this.manufacturer = manufacturer;
this.model = model;
this.price = price;
this.yearOfMfr = yearOfMfr;
this.dateBought = dateBought;
this.licenceNumber = licenceNumber;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getYearOfMfr() {
return yearOfMfr;
}
public void setYearOfMfr(int yearOfMfr) {
this.yearOfMfr = yearOfMfr;
}
public Date getDateBought() {
return dateBought;
}
public void setDateBought(Date dateBought) {
this.dateBought = dateBought;
}
public String getLicenceNumber() {
return licenceNumber;
}
public void setLicenceNumber(String licenceNumber) {
this.licenceNumber = licenceNumber;
}
}
public class DemoApp {
public static void main(String[] args) {
List<Object> results = new ArrayList<>();
DemoApp app = new DemoApp();
app.fillItUp(results);
Car acar = (Car) results.get(0);
acar.setLicenceNumber("Flying Duck");
}
private void fillItUp(List<Object> results) {
Car car = new Car("sel2in", "electric_VTOL", 540923, 2018, new Date(2018, 3, 32), "Skyprog");
results.add(car);
results.add(new Person("tushar", 39));
}
}

How to reference a extended subclass in java?

I am currently working on a project for java and the teacher isn't very great at explaining himself.
Currently I'm stuck trying to reference an extended Class in java to get the balance. (i'm trying to edit the balance so that it can be displayed and changed in the array.
my main account looks like this
public class Account {
private String name;
private double quantity, price;
private double rate;
private Asset[] Asset;
}
The account that is extended is
abstract public class Asset {
String symbol;
public String getSymbol() {
return symbol;
}
protected Asset(String symbol) {
this.symbol = symbol;
}
}
The extensions look like so;
public class Cash extends Asset {
private double Quantity;
public Cash(double Quantity, String symbol) {
super(symbol);
this.Quantity = Quantity;
}
#Override
public String getSymbol() {
return super.getSymbol(); //To change body of generated methods, choose Tools | Templates.
}
public double getQuantity() {
return Quantity;
}
public void setQuantity(double Quantity) {
this.Quantity = Quantity;
}
}
Now lets say I have a test instance created of class Account.
How would I be able to edit the Cash value from the Class account? (Main arg)
Here are the other extensions I have too just for reference.
public class Stock extends Asset {
private String name;
private double quantity, rate;
public Stock(String name, double quantity, double rate, String symbol) {
super(symbol);
this.name = name;
this.quantity = quantity;
this.rate = rate;
}
#Override
public String getSymbol() {
return super.getSymbol(); //To change body of generated methods, choose Tools | Templates.
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getQuantity() {
return quantity;
}
public void setQuantity(double quantity) {
this.quantity = quantity;
}
public double getRate() {
return rate;
}
public void setRate(double rate) {
this.rate = rate;
}
}
If it helps, how would I be able to change the values in the extended classes?
I've tried
Asset[0] = new Cash(25000.00,string);
but that's only helpful in putting the value manually.
Apologies for any mistakes, I'm pretty new to coding and java in general.
The way you named your Asset array is confusing, java is case sensitive so name it for example:
private Asset[] asset;
You need to get a reference of the right type through casting before you can access it's own methods. You can do for example:
if (asset[0] instanceof Cash) {
Cash cash = (Cash)asset[0];
// Then you can access the setQuantity method
cash.setQuantity(25000.00);
}

Create a method with unknown number and type of arguments in java

I'm working with primefaces datatables, and at the same time I'm using Triple datastores (Jena TDB) instead of traditional databases. I'm going to create an object like primefaces showcase sample below;
public class Car {
private String model;
private int year;
private String manufacturer;
private String color;
public Car(String model, int year, String manufacturer, String color) {
this.model = model;
this.year = year;
this.manufacturer = manufacturer;
this.color = color;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
here everything is clear and car object has definite arguments like model, year, ... however in my program based on user selection from the menu bar, I have to call quite different objects with various properties as arguments and do the same as shown in the showcase. I'm quite new in java and I really confused how can I solve this problem.
As an example my program object could be a company with (Name, Address, Email, Tel ,... ) arguments, or it could be a Machine with quite different properties like (Name, Model, production date, Specs. and etc).
Thanks in advance for your responses.
Not exactly understood the explanation you have provided. I can give you one answer against your title: Create a method with unknown number and type of arguments in java
You can use Java args along with Object class.
package com.misc;
public class NNumberOfObj {
public static void acceptNNumberOfAnyTypeofObjects(Object... args) {
System.out.println("Total objects are: " + args.length);
//Your further implementation goes here.
}
public static void main(String[] args) {
String s = new String("Nikhil");
Integer i = 10;
Employee emp = new Employee(10, "Kunal");
acceptNNumberOfAnyTypeofObjects(s, i, emp);
}
}
class Employee {
private int id;
private String name;
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
}

Categories