how do I pass subclass parameters into the superclass private variables? - java

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.
}

Related

Creating a superclass and subclass with constructors - Java

I am new to Java. I have a problem to solve, but I don't quite understand how constructors work. I understand how to create a superclass and a subclass but I don't understand the constuctors within them (or how they actually work - I have done rediculous amounts of research on constructors, but it's just not making much sense).
I am trying to write a program that creates a superclass called Employees. This Employee class has instance variables employeeId (which is an integer) and employeeName (which is a String).
The subclass is called Manager. The Manager subclass has an instance variable called employeeTitle (which is a String). It also has a method with the name of managerDetails(). ManagerDetails() is supposed to display the employeeId, employeeName, and the employeeTitle.
This is what I have so far:
package tryingoutjava;
public class TryingOutJava {
class Employee {
int employeeId;
String employeeName;
void Employee() {
}
}
class Manager extends Employee {
String employeeTitle;
void managerDetails() {
}
}
public static void main(String[] args) {
}
}
I am very confused on how to set up the constructors for the superclass and the subclass, or even what a constructor really looks like. I've seen examples all over the internet, but no one actually highlights the actual part that is the constructor, or how everything is linked visually, which is what helps me learn.
I guess I'm also having issues with understanding how to set up a method that calls on an object. If anyone has the time to help, it would greatly be appreciated. Thanks!
I guess you want something like this. Be noted, that it is a good idea to separate classes one-per-file in this case, as they are separate entities here. It is a good idea to limit data access to entity fields, as such using encapsulation.
Employee.java:
package tryingoutjava;
public class Employee {
// Protected access because we want it in Manager
protected int employeeId;
protected String employeeName;
public Employee(int employeeId, String employeeName) {
this.employeeId = employeeId;
this.employeeName = employeeName;
}
}
Manager.java:
package tryingoutjava;
public class Manager extends Employee {
private String employeeTitle;
public Manager(String employeeTitle, int employeeId, String employeeName) {
// Use super to invoke Employee constructor
super(employeeId, employeeName);
this.employeeTitle = employeeTitle;
}
// Just create a simple string describing manager
#Override
public String toString() {
return "Manager{" +
"employeeTitle='" + employeeTitle +
"employeeId=" + employeeId +
", employeeName='" + employeeName + '\'' +
'}';
}
}
Application.java:
package tryingoutjava;
public class Application {
// Example of construction plus printing of Manager data
public static void main(String[] args) {
Employee davie = new Employee(1, "Dave The Cable Guy");
Manager tom = new Manager("CFO", 2, "Tomas");
System.out.println(tom.toString());
}
}
Constructors (most often than not) just delegate construction of parent through super invocation. While there are other techniques, like Builder pattern, this is the most basic and understandable approach. There are several other ways to do this, but this should get you started, hope it helps!
Purpose of Constructor
constructor is a method like other method but it is called when instantiate (or create a object from your class) for initialize your object for first use or later use. for example a class like Student must created (instantiated) when we give it name and family name for example. Without them, create a Student is not good because maybe we forget to give it proper name and use it incorrectly. constructor forces us to provide minimum things needed for instantiating objects from classes.
Constructor implementation in inheritance
About inheritance, it is different. When you want to create a Student which is a Human (extends Human) you must first create Human inside your Student and set special feature for your Student like ID which is not for Human (Human has name and etc). so when you create a Student with constructor, the super constructor (for Human) is called too.
What do we do in constructor
as I mentioned, we provide default value for our properties which must set them before creating and using object. (for using them properly) every subclass call super class constructor implicitly with super() but if super class doesn't have any default constructor (constructor with no argument) you must explicitly say super(...) at the first lien of subclass constructor (otherwise compile error)
What is the program steps when using constructor (Advanced)
super class static constructor and static variable (read by self if you want to know more about things I say here)
subclass class static constructor and static variable
super class variable and block constructor
super class constructors
sub class variable and block constructor
sub class constructors
I only mentioned 4 & 6.
I try to explain completely. My English is not good. I'm sorry.
If you know how a method works, then you know how a constructor works. The constructor is simply a special method that allows you to execute some code before the object is created.
Person p = new Person("Bob", 25); // Calls constructor Person(String name, int age)
Then in the constructor you can do things like assign initial values to any instance variables.
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
If the class is a subclass you need to call a constructor of the parent class before the object is created unless the parent class has a constructor with no parameter in which case java can call it for you if you don't specify anything. Here Worker extends Person.
private String occupation;
public Worker(String name, int age, String occupation) {
super(name, age) // Calls constructor Person(String name, int age)
this.occupation = occupation;
}
I guess you can achieve what you want in a single file via the code snippet below:
You can copy paste it in your code and it should work.
You can see how the constructor of parent class is being called by the help of super() and also the methods. Here I have used methods like getEmployeeTitle() which should help you get an overview on how to write methods. I have also overridden the toString() method so that you can understand how to override Object class' useful methods like toString().
Note : Although I have created all the classes in one code snippet for the sake of simplicity , but it is highly recommended that you create a separate file for each of these classes.
class Employee {
int employeeId;
String employeeName;
Employee(int employeeId, String employeeName) {
this.employeeId = employeeId;
this.employeeName = employeeName;
}
}
class Manager extends Employee {
private String employeeTitle;
Manager(int employeeId, String employeeName, String employeeTitle) {
super(employeeId, employeeName);
this.employeeTitle = employeeTitle;
}
public String getEmployeeTitle() {
return employeeTitle;
}
#Override
public String toString() {
return ("employeeId: " + employeeId + ", employeeName: " + employeeName + ", employeeTitle" + employeeTitle);
}
}
public class TryingOutJava {
public static void main(String[] args) {
Manager manager = new Manager(007, "John Doe", " Sr. Manager");
System.out.println(manager);
System.out.println(manager.getEmployeeTitle());
}
}

In Java is it correct to allow subclass to alter superclass private fields via public setter method?

Please look at the code below
Class Employee{
private String name;
private String id;
public String getName(){ return name; }
public void setName(String name){ this.name = name; }
public String getId(){ return id; }
public void setId(String id){ this.id = id; }
}
Class Teacher extends Employee{
private double salary;
}
Now my question is If I am creating an object of Teacher , then it does not make sense without the Teacher object having a name and id. I can set the same for teacher object via public setters of Employee but it it correct ?
Teacher t1 = new Teacher();
t1.setName("aaa");
t1.setId("224");
t1.salary = 200.00;
System.out.println(t1.toString());
I am asking this question as my understanding is if the field is private it should be used only via getters . But in the example provided above Teacher object will not make sense without having a Name or Id .
If it is correct then why not make the field public in the first place? What is the advantage in using it private and then allowing access via public setter ?
If it is not correct please provide an example of how the above Employee and Teacher class should be implemented ?
Your question seem to show a confusion between two concepts rather independant:
encapsulation
creation of objects
Encapsulation: it is better design to define private variables. Then you can not corrupt the object from outside. You must use setter to modify your employee.
But, if you trust Teacher, it could modify Employee as a subclass, without setter, it is faster to code (but little risky: if you have to change the setter in employee, Teacher wont get it, ...).
Creation of objects: you should pass certain values to the variables, or they are defined by default (or auto-built ...)
=> you can decide that Teacher have well defined values (default), or that you must give these values (mandatory). It is your design.
After that, you can change them directly or by setters of Employee (=> first concept of encapsulation).
then it does not make sense without the Teacher object having a name and id. I can set the same for teacher object via public setters of Employee but it it correct ?
This is where exactly constructor comes into picture. You need to pass them before you are using it.
Thumbrule : When you want something while building it, you need to force them to pass on constructor.

Inheritance, deriving from a derived class

I am trying to create a class from a class that is already derived from another class. (bit confusing) It adds one extra attribute in the newest "PricedApt" class that is "price". The desired constructor call is as follows
PricedApt p = new PricedApt("jill", 900, true, "jack", 1050.00);
The class is missing its constructor and im trying to create it but not sure whats wrong.
This is the (already derived (2nd) class)
public class RentalApt extends Apartment{
private String tenant;
private boolean rented;
public RentalApt(String owner, int size, boolean rented, String who){
super(owner,size);
tenant = who;
this.rented = rented;
}
My code for the (3rd) class that I have attempted is
public class PricedApt extends RentalApt {
private double price;
public PricedApt(String owner, int size, boolean rented, String who, double priceTag) {
super(owner,size,who);
price = priceTag;
}
}
Can anyone point me in the right direction as to what I am doing incorrectly? The compilation error I'm receiving is cannot find symbol (line 2 column 3).
For one, RentalApt has a four-argument constructor, but its subclass PricedApt is calling super() with only three arguments.
Try changing
super(owner,size,who);
to:
super(owner,size,rented,who);

Can I make new methods dynamicly in a loop or in an other matter

In school we have to make a program, which is that you type in personal information, such as namn, age and so on. And you have one button where you save information and one where you type out.
I save this information like this:
Person.name = Name.getText();
Person.age = age.getText();
Person.sex = sex.getText();
And then i have a method. Which takes this information and saves it. Because there is only one button to save information. Can you make new mothods for every new person you save? Should you do it in a loop. That loops out new methods everytime you press? And how.
Thx
You do not need to 'make new methods' each time you want to save the Person data. The point is to create a method which is dynamic, that means you have to have access to the Person class/data and just do as you defined: person.setName(name.getText());
You dont need a new method everytime you save, you need a new Person object. The method that gets called when save is pressed should accept Person as a parameter. So save is pressed it creates a new Person object and populates it like u already do, Person.name = Name.getText();, Person.age = age.getText(); and so on. That populated Person object is then passed to a method which has all the code to save it.
You do not need to make new method every time, what you need to do is just make a class named Person and define its attributes as Name, Age and Sex and make methods that access this variables and sets this variables, as I've shown below:
class Person{
String Name="";
String Age="";
String Sex="";
public String getName(){
return Name;
}
public String setName(String Name){
this.Name=Name;
}
public String getAge(){
return Age;
}
public String setAge(String Age){
this.Age=Age;
}
public String getSex(){
return Name;
}
public String setName(String Sex){
this.Sex=Sex;
}
}
You can access this methods and variables by just making object of this Person class as:
Class UsePerson{
public static void main(String ar[]){
Person p=new Person();
p.setName("ABC"); //Here You set the Name of the person
String name=p.getName(); //Here you'll get the name of Person
}
}

Methods and Composition java

I have a facade engine with a method
getOwner()
I also have another class called Car and another caller Owner. Car class also has a getOwner() method while the Owner class contains the name, the cost of the car and the budget of the owner.
So I have a method to initialize the engine and this calls the constructor in the newCARengine class.
public static void iniEngine(String name, int cost) {
model = new newCARengine(name, cost);
}
Composition. The engine class has a car, and the car class has an owner. For me to successfully call the getOwner() method I need to use instance variables (class level variable) to hold a reference to the other object in order to call that method from that object.
MY ENGINE CLASS: [below]
public class engine{
private String name;
private int cost;
public Car car;
public engine(String name, int cost){
this.name = name;
this.cost = cost;
}
public Owner getOwner(){
return car.getOwner();
}
}
I'm referencing the Car class by using an instance variable for that class "public Car car;" which then allows me to use "car.getOwner();" method.
MY CAR CLASS: [below]
public class Car{
public Owner owner //instance variable to reference the owner class
public Owner getOwner(){
return owner;
}
}
Now i'm ready to go to the Owner class where the Owner object is created.
MY OWNER CLASS: [below]
public class Owner{
private String name;
private int cost;
private int budget;
public Owner (String name, int cost){
this.name = name;
this.cost = cost;
}
public Owner (String name, int cost, int budget){
this.name = name;
this.cost = cost;
this.budget = budget;
}
public String getName(){return name;}
public int getCost(){return cost;}
public int getBudget(){return budget;}
}
Now I am doing something wrong as when I run the iniEngine() method, I get a nullpointer exception and this I belive is a result of the object not being created. The error is generated from here:
return car.getOwner(); //from the ENGINE CLASS
I need to return an object as a result of my engine class. but the object is not getting created. Any assistance would be appreciated.
I reviewed your code several times. I don't understand where you associate an owner to a car.
This is what causes the NullPointerException
I suggest you provide a CTOR to Car that gets Owner as parameter and in addition, consider having a setCar method.
Consider using the following code for Car:
public class Car{
public class Car(Owner owner) {
this.owner = owner;
}
private Owner owner //instance variable to reference the owner class
public void setOwner(Owner owner) {
this.owner = owner;
}
public Owner getOwner(){
return owner;
}
}
Style note: in Engine, car should probably also be private, just like the other fields, with either a setter, or a constructor argument.
It seems like some of the fields are not getting set. One debugging "trick" I use in similar cases is to temporarily make the fields final, and see what the compiler complains about. For example, if anybody is setting engine.car, it would complain. In this case, that is a good thing - it should be complaining! And, if nobody is setting engine.car, that's a red flag as to where the NPE is coming from.
Alternatively, if you do have setters/getters, put breakpoints in them (or, if you prefer, add System.out.prints) to verify that they are getting called. Or, temporarily rename them (I add "xxx" to the beginning) to verify that the compiler complains, proving that somebody is calling them.
I never instantiated the objects and only delcared the variables.
By changing the constructor to
public Engine(String name, int cost) {
car = new Car(new Owner(name, cost));
}
This created the objects successfully which in turn allowed me to call the getOwner() method and not get any NullPointerExceptions. Must have missed this part somehow.

Categories

Resources