Hi I am a beginning programmer and I think I have a simple question but yet i can't find the answer. I hope you can help me:D I have four classes in total but what I need to solve is in class Person. I have a simple method that needs thePrice parameter from class Product. But it does not work because i can't get access to this parameter.
This is the method that the Person class uses to buy a product. The budget from a person has to be greater or equal to thePrice, if not > he can not buy the product. But he can only buy the product if he has not owned the product already.
public class Person{
private String name;
private double budget;
private ArrayList<Product> allPossessions;
private Product theProduct; //association with class product, I have all getters and setters etc.
// the method:::
public boolean Buy(Product p) {
if (hasProduct(null) == true) {
if (budget >= Product.getThePrice()) {
// getTheprice does not work, how do i get this working? How do i get this parameter from class product?
return true;
}
return false;
}
return false;
}
This is class Product where I need to have thePrice, to create the method.
public abstract class Product {
protected String Design;
protected int yearOfPurchase;
protected double thePrice;
}
Thank you for your time and forgive my broken english! Thank you:)
You should write a getter method for thePrice param inside Product class.
public double getPrice() {
return thePrice;
}
Related
I think explaining my question via code is easier.
Given a sales company which has 2 sales employee for example:
public class Employee()
{
private int salary;
}
public class SalesEmployee1 extends Employee()
{
private int commisionRate;
}
public class SalesEmployee2 extends Employee()
{
private int commisionRate;
}
Suppose I have a vector: Vector<Employee> v = new Vector<>();
I need to iterate over that vector and find the SalesEmployee1 with the lowest commission(each salesEmployee computes it differently so its a different commission) .
How can I ask whether I am a SalesEmployee1 without using instanceof?
I thought about adding a function in the father class which every child overrides
public boolean myClass(String name)
{
return name.equals(ClassName for example SalesEmployee1);
}
and than do something like that:
for(Employee e : v)
{
if(e.myClass("SalesEmployee1")
doSmth()...
}
Is this method right? can anyone suggest another solution because I feel like im doing somthing wrong because this feels like a instance of variation.
Thanks!
The whole purpose of object-orientated programming, is that each (sub-)class knows its own behaviour. There should be no need to detect the specific class of an object at run-time. It an indication that something is wrong in your design, if you feel the need to detect the class of an object.
The different types of employees should know themselves how to calculate the commission:
public class Employee()
{
abstract int calculateCommission();
}
public class SalesEmployee1 extends Employee()
{
int calculateCommission() { ... }
}
public class SalesEmployee2 extends Employee()
{
int calculateCommission() { ...}
}
Then you can through all Employees to find the lowest commission:
for(Employee e : v) {
int commission = e.calculateCommission();
// do something with the commission;
}
public class ClassA_V01 {
private String name;
private int age;
// getter and setter
}
public class ClassA_V02 {
private String name;
private int age;
private int gender;
// getter and setter
}
public static void main(String[] args) {
SomeClass classA = new ClassA_V01();
classA.setName("myName);
classA.setAge(99);
performLogic(classA);
// OR
SomeClass classA = new ClassA_V02();
classA.setName("myName);
classA.setAge(99);
classA.setAge(1);
performLogic(classA);
}
public void performLogic(SomeClass classA) {
// do something
}
For strategy pattern to work, both classes must implement the same methods defined in the interface. But what if the classes need to have different fields and methods?
In my example, ClassA_V01 and ClassA_V02 are the same class except that one has more attribute "gender"
How does one implement the above such that classA can be equals to either ClassA_V01() or ClassA_V02?
"...For strategy pattern to work, both classes must implement the same methods defined in the interface. But what if the classes need to have different fields and methods?..." really this is not a criteria for strategy pattern.
Strategy pattern's intent is to identify and make family of algorithms interchangeable. If you read the pattern's documentation carefully, Strategy can be used when many related classes differ only in their behavior.
Appropriate decomposition is the key for better (extendable) design. A typical (but primitive) solution to Employee assignment, sub-classing tempEmp and permanentEmp types will put us in trouble and will not allow temp employee to become permanent in its life time (which has no meaning in real terms). This happens because we miss an important point- each employees employeeness is not different, they are all same type of employees with different pay policies. (same logic can be extended for Leave policy and so on)
This becomes simple if all types of employees have Salary computation based on same components (same state). But your question is what if TempEmployee gets only basicPay whereas PermanentEmployee gets basicPay as well as travelAllowance (additional attribute which is not present for TempEmp). This can be modeled by a combination of simple inheritance hierarchy along with strategy taking care of computation algorithm dependent upon Employee's (aka. Context) attribute (age)
public class Employee {
//name and id
private PayPackage payPackage;
private int age;
PayPackage strategy;
public double computeSalary() {
return payPackage.computePay(age);
}
//get/setPayPackage(...)
}
public abstract class PayPackage {
private double basicPay;
abstract public double computePay(int age);
protected double getBasicPay(){
return basicPay;
}
}
public class TempPayPackage extends PayPackage{
#Override
public double computePay(int age) {
double veteranAllowance = 0;
if (age > 40) {
veteranAllowance = 2000.00;
}
return getBasicPay() + veteranAllowance;
}
}
public class PermanentPayPackage extends PayPackage{
private double travelAllowance;
#Override
public double computePay(int age) {
double veteranAllowance = 0;
if (age > 40) {
veteranAllowance = 5000.00;
}
return getBasicPay() + travelAllowance + veteranAllowance;
}
}
Important thing to remember is Design patterns never work alone or as an alternative, they work hand in hand with Object oriented code and other patterns.
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 am confused on how to get parameters from new object instances to also flow into the super class to update the private fields in teh super class.
So I am in an advanced Java class and I have homework that requires a "Person" Super Class and a "Student" subclass that extends Person.
The Person class stores the student name BUT it is the Student class constructor that accepts the Person name.
assume no method in Person to make a variable method update...like subClassVar = setSuperClassVar();
EX:
public class Person
{
private String name; //holds the name of the person
private boolean mood; //holds the mood happy or sad for the person
private int dollars; //holds their bank account balance
}
class Student extends Person //I also have a tutor class that will extend Person as well
{
private String degreeMajor //holds the var for the student's major they have for their degree
Public Student(String startName, int startDollars, boolean startMood, String major)
{
degreeMajor = major; // easily passed to the Student class
name = startName; //can't pass cause private in super class?
mood = startMood; //can't pass cause private in super class?
dollars = startDollars; // see above comments
// or I can try to pass vars as below as alternate solution...
setName() = startName; // setName() would be a setter method in the superclass to...
// ...update the name var in the Person Superclass. Possible?
setMood() = startMood; // as above
// These methods do not yet exist and I am only semi confident on their "exact"...
// ...coding to make them work but I think I could manage.
}
}
The instructions for the homework were a bit vague in terms of how much changing to the superclass of Person I am allowed to make so if you all believe a good solid industry accepted solution involves changing the superclass I will do that.
Some possible examples I see would be to make the private vars in Person class "protected" or to add setMethods() in the person class and then call them in the sub class.
I am also open to general concept education on how to pass subclass contstructor parameters to a super class...and if possible do that right in the constructor portion of the code.
Lastly, I did search around but most of the similiar questions were really specific and complicated code....I couldnt find anything straight forward like my example above...also for some reason the forum post did not clump all of my code together so sorry for the confusing read above.
Thanks all.
First, you need to define a constructor for Person:
public Person(String startName, int startDollars, boolean startMood)
{
name = startName;
dollars = startDollars;
mood = startMood;
}
Then you can pass data up from the Student constructor using super(...):
public Student(String startName, int startDollars, boolean startMood, String major)
{
super(startName, startDollars, startMood);
. . .
}
Alternatively, you can define setters in the Person class and invoke them from the Student constructor.
public class Person
{
private String name; //holds the name of the person
private boolean mood; //holds the mood happy or sad for the person
private int dollars; //holds their bank account balance
public void setName(String name) {
this.name = name;
}
// etc.
}
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Property and Encapsulation
NEWB Alert!!
I am starting with Android and Java and I am starting to understand it but I am wondering why I should use getters and setters and not just public variables?
I see many people make a private variable and create a get and set method.
What is the idea here?
Its called encapsulation and the concept is central to object oriented programming. The idea is that you hide the implementation of your class and expose only the contract i.e. hide the how and only expose the what. You hide the variables by making them private and provide public setters-getters and other public methods which the clients invoke to communicate with your class. They are not tied to the actual implementation of the methods or how you store your variables.
For example, suppose you had this class where you stored a phone number as a Long object:
public class ContactInfo {
private Long phoneNo;
public Long getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(Long phoneNo) {
this.phoneNo = phoneNo;
}
}
Since the clients of the class only see the getter/setter, you can easily change the implementation of the class/methods by switching the phone number representation to a PhoneNumber object. Clients of ContactInfo wouldn't get affected at all:
public class ContactInfo {
private PhoneNumber phoneNo;
public Long getPhoneNo() {
return phoneNo.getNumber();
}
public void setPhoneNo(Long phoneNo) {
this.phoneNo = new PhoneNumber(phoneNo);
}
}
public class PhoneNumber {
private Long number;
public PhoneNumber(Long number) {
this.number = number;
}
public Long getNumber() {
return number;
}
}
The OOP concept involved is encapsulation (google it).
Some of the advantages are: you can specify different access level for setters (mutators) and getters (accessors), for example public getter and private setter. Another advantage is that you can add another code other than changing or retrieving the value. For example, you may want to check the validity of the set value, or you want to throw exceptions or raise some events in response to changing the variable to certain value. If you implement these inside an accessor or mutators, you can also change their implementations without changing any code outside of the class.
I believe the idea is "information hiding" http://en.wikipedia.org/wiki/Information_hiding
It also serves to control the access to variables (provides an interface). For example, you can provide a getter but not a setter, so that they may be read but not written. Whereas if everything was public any thing could read and write to the variables.
Also important is any checking/validation need to set a variable. For example you have a String name that is not allowed to be empty but if it is public it could easily be forgotten and set as name = "". If you have a setter such as public boolean setName(String newName) you can check newNames length and return true or false if it passes and is set or not
The concept is called encapsulation.
What it attempts to do is to separate the inner structure of a class from its behaviour.
For example, suppose a class like this
public class Point{
private float x;
private float y;
public float getX(){
return x;
}
public float getY(){
return y;
}
public float distanceToZero2(){
return x*x + y*y
}
public float getAngle(){
//havent considered the x = 0 case.
return atan(y/x);
}
public boolean isInFirstQuad(){
return x>0 && y>0;
}
}
In this case, encapsulation hides the inner structure of the class, and exposes only the operations available to a Point. If you dont like it, you can change its inner structure and mantain its behaviour (for example, changing carthesian coordinates to polar coordinates).
Anyoune who uses this class wont care about it, he /she will be happy that they have a Point class with this functionality.
Asides the encapsulation, you can also control the value get or set to your variable in some cases. For example, you want to validate the value of an age variable which should be >=1
class Person {
private int age = Integer.MIN_VALUE;
public void setAge(int age){
if(age>=1)
this.age = age;
}
public int getAge(){
return age;
}
}