returning a private static variable - java

I am having trouble returning my static private variable personCount. This variable simply counts the amount of people i add into my program, in my constructor for Person i set it so every time a person was entered, personCount incremented by 1. I have also created a getPersonCount method which simply returns the int value of personCount.
My problem is that when trying to implement this method in my test file, I am unsure on how to call the method, and get the value of personCount logged to the output.
I'm not sure if i am a million miles away or a small syntax error away, so any help would be much appreciated!
My Person constructor:
public Person(String foreName, String surName, int age,
double height, String gender)
{
this.foreName = foreName;
this.surName = surName;
this.age = age;
this.height = height;
this.gender = gender;
personCount = personCount +1;
}
My getPersonCount method:
public int getPersonCount()
{
return personCount;
}
My attempt to call the method in my test drive:
System.out.println(getPersonCount());
Please let me know if any more code is needed.

Try this, make your method definition in class Person like:
public static int getPersonCount() { //<-- note the static modifier
return personCount;
}
To invoke it:
System.out.println(Person.getPersonCount());//<-- use class name, if your using this method outside the class

You have two choices:
public static int getPersonCount() {
return personCount;
}
with the corresponding call:
Person.getPersonCount();
OR:
public int getPersonCount() {
return personCount;
}
and the corresponding call:
myPersonInstance.getPersonCount();
So in the last case, you deal with a Person instance.

public static int getPersonCount(){
return personCount;
}
Then invoke above method
Person.getPersonCount();

Related

My getMethod does not return the value in the setMethod: Java

public class OOP_10_Encapsulation {
private String firstName;
private String favFood;
private int age;
private float weight;
//create a set method for firstName
public void setFirstName(String firstName){
this.firstName = firstName;
}
//create a get method for firstName
public String getFirstName(String firstName){
this.firstName = firstName;
return firstName;
}
//create a set method for favFood
public void setFavFood(String favFood){
this.favFood = favFood;
}
//create get method for favFood
public String getFavFood(String favFood){
this.favFood = favFood;
return favFood;
}
//create a set method for age
public void setAge(int age){
this.age = age;
}
//create a get method for age
public int getAge(int age){
this.age = age;
return age;
}
//create a set method for weight
public void setWeight(float weight){
this.weight = weight;
}
//create a get method for weight
public float getWeight(float weight){
this.weight = weight;
return weight;
}
}
public class OOP_11_TestEncapsulation {
public static void main(String[] args) {
OOP_10_Encapsulation learner1 = new OOP_10_Encapsulation(); //create object of OOP_10_Encapsulation
learner1.setFirstName("Evander O A");
learner1.setAge(31);
learner1.setWeight(98.6F);
learner1.setFavFood("waakye");
System.out.println("Hi, my name is " + learner1.getFirstName());
}
}
I have this challenge that I am not able to get my head around. When I run the code in the main method, the get method does not return the name "Evander O A" as set in the set method. Actually, none of my get methods are getting anything I need them to get.
Let's look at one of your get methods:
//create a get method for age
public int getAge(int age){
this.age = age;
return age;
}
The purpose of a get method, also called "getter" is to get something from inside an object, usually it's some of the object's attribute that you wanna get.
If you just want to get an attribute, there is no need to pass a parameter to the get method:
public int getAge(int age) // age parameter is useless
Not only that it is useless here, but you are also doing something wrong, in the get method you are first changing attribute's value. You are effectively doing a set inside a getter method:
this.age = age; // wrong
Given your code for getAge method, let's see how it will execute when you call something like:
System.out.println("Hi, my name is " + learner1.getAge())
The function getAge will be called with no parameter, although it is expecting one. So most probably you won't be able to compile this piece of code.
I got the following error when trying to compile something similar:
https://imgur.com/a/4AVwMke
So if you create a function with 1, 2, 3 or whatever number of parameters then you must call it using the same number of arguments to the function call. Otherwise most probably that code won't run.
Now let's assume I call it with some value as argument, probably you did too.
System.out.println("Hi, my name is " + learner1.getAge(0))
This is going to happen:
//create a get method for age
public int getAge(int age // which is 0){
this.age = age; // you set the age to 0, losing the old value
return age; // you return 0, because you no longer have the old value
}
How should you do it? Simple:
//create a get method for age
public int getAge(){
return age;
}
Now apply this fix to all of your getters (the get methods) and you are good to go. Let me know if something is not clear.

Correct way to build constructors in a subclass that extends to a subclass of a superclass

edit: added employee constructors;
my question involves constructor chaining for a subclass (to a super which is itself a subclass). I have written constructors that seem to work, but I feel that they are incorrectly written as I will explain. PTEmployee extends to Employee who is extended to a Person. The code below seems to work in my test class,
public class PartTimeEmployee extends Employee {
public static final int DEFAULT_HOURSPRWK = 0;
private int hoursPerWk;
public PartTimeEmployee() {
this(DEFAULT_HOURSPRWK);
}
public PartTimeEmployee(int hoursPerWk) {
this(DEFAULT_HIRE_DATE, DEFAULT_INCOME, hoursPerWk);
}
public PartTimeEmployee(String hireDate, double incomeWk, int hoursPerWk) {
super(hireDate, incomeWk);
this.hoursPerWk = hoursPerWk; // I dont think I need two this.var?
}
public PartTimeEmployee(String firstName, String surname, int age, Address address, String hireDate, double incomeWk, int hoursPerWk) {
super(firstName, surname, age, address, hireDate, incomeWk);
this.hoursPerWk = hoursPerWk;
}
But I feel that the use of two constructors with (super) and this.hoursPerWk = hoursPerWk is wrong, shouldn't '(super)' and 'this.var = var' only need to be written once? If I adjust the code to remove the PTEmp(hiredate, incomewk, hrswk) constructor than I get a 'no constructor found' error in my second constructor. Other edits have led to recursor errors.
So the supplied code works and calls all details in my test class, but is it correctly written (I need to have a Person class that is extended by Employee which is extended by PTEmp or Boss etc.). Appreciate any feedback (or jsut to know this is correct if it is.
Thanks.
Added Employee constructors here...
public class Employee extends Person {
public static final String DEFAULT_HIRE_DATE = "00/00/00";
public static final double DEFAULT_INCOME = 0;
private String hireDate;
private double incomeWk;
public Employee() {
this(DEFAULT_HIRE_DATE, DEFAULT_INCOME);
}
public Employee(String hireDate, double incomeWk) {
this(DEFAULT_FIRSTNAME, DEFAULT_SURNAME, DEFAULT_AGE, new Address(), hireDate, incomeWk);
}
public Employee(String firstName, String surname, int age, Address address, String hireDate, double incomeWk) {
super(firstName, surname, age, address);
this.hireDate = hireDate;
this.incomeWk = incomeWk;
}
Not sure what super() does if you don't specify names, address, etc, but assuming that you can use some defaults, maybe you can call it like this:
public PartTimeEmployee(String hireDate, double incomeWk, int hoursPerWk) {
this(DEFAULT_FIRST_NAME, DEFAULT_SURNAME, DEFAULT_AGE, DEFAULT_ADDRESS, hireDate, incomeWk, hoursPerWk);
}
Consider using builder patterns, if you think that you have too many overloaded constructors:
When would you use the Builder Pattern?

it's print null in console when I run a program in Java

`
package Stuff;
public class Student{
private String name;
private int age;
public Student(String studentName,int studentAge){
studentName = name;
studentAge = age;
}
public void printName(){
System.out.println(name);
}
public void printAge(){
System.out.println(age);
}
public void printInfo(){
System.out.println(name);
System.out.println(age);
}
public static void main(String[] arg0){
Student student1;
student1 = new Student("ragaey",22);
student1.printInfo();
}
}
`
I Don't Know where is the wrong in code the console print me (null) when i request student1.printName() and 0 When i request Student.printAge()
Your variable assignments in the constructor are the wrong way around.
You are assigning the variables in the constructor in wrong way. The correct way will be:
public Student(String studentName,int studentAge){
name = studentName;
age = studentAge;
}
If you auto-generate the constructors then it will look like this, which is more common convention:
public Student(String name,int age){
this.name = name;
this.age = age;
}
You messed up the initialization part studentname = name and studentage = age the right way of initialization is given down
public class Student{
private String name;
private int age;
public Student(String studentName,int studentAge){
name = studentName;
age = studentAge;
}
public void printName(){
System.out.println(name);
}
public void printAge(){
System.out.println(age);
}
public void printInfo(){
System.out.println(name);
System.out.println(age);
}
public static void main(String[] arg0){
Student student1;
student1 = new Student("ragaey",22);
student1.printInfo();
}
}
The constructor should be like
public Student(String studentName,int studentAge){
this.name = studentName;
this.age = studentAge;
}
I highly recommend that you have a look at this article on associativity in Java.
Basically, when you assign a value to a variable using the = operator, the statement is carried out from right to left. Hence, the outcome of the expression on the Right Hand Side is assigned to the variable on the Left Hand Side.
Hence, int a = 5+5 means that the outcome of 5+5 is stored in variable a. This is also why studentName = name assigns the value of name (which is the default value of the String type - null) to studentName.
It is also important to note that null is a keyword in Java, and if you print null like this:
System.out.println(null)
A Syntax Error will be thrown (which is for a different reason).
EDIT - At the time of typing this out, there was only one answer, and not explanatory in any way. Now, I see there are more. Although the other answers may tell you what to do, I figured that this answer would tell you how to think in Java, so that you make no such mistakes again.

Using Eclipse, trying to get a program to work

I am currently learning Java with eclipse for my computer science course, and I need some assistance trying to figure out how to fix the error that is currently showing.
package sec4Les2;
public class RoseDS4L2Person {
//creating the variables
public String name = "Uma Thurman";
public int Age = 0;
//constructor
public RoseDS4L2Person()
{
}
public String getname()
{
//will return first name
return name;
}
public int getAge()
{
//will return age
return Age;
}
public void setAge(int Age)
{
//will set age to int
this.Age = Age;
}
}
And here is the running code:
package sec4Les2;
public class RoseDS4L2ManagingPeople {
public static void main(String[] args) {
//runs information in first class file
RoseDS4L2Person p1 = new RoseDS4L2Person("Arial", 37);
RoseDS4L2Person p2 = new RoseDS4L2Person ("Joseph", 15);
if(p1.getAge()==p2.getAge())
{
System.out.println(p1.getname()+" is the same age as "+p2.getname());
}
else
{
System.out.println(p1.getname()+" is NOT the same age as "+p2.getname());
}
}
}
It says there are no errors on the first one, but the second one has errors on the p1/p2 lines. How can I fix this error? thank you!
You should have a constructor for RoseDS4L2Person accepting a string and a number, like so:
public RoseDS4L2Person(String name, int age)
{
this.name = name;
this.Age = age;
}
This will allow you to create an instance of the class passing a name and an age as parameters.
You need to add this code to your class. Basically, a constructor was missing in your class. Also note that by convention, member variables start in lowercase. So your Age should really be age.
Another thing is, you have kept name as constant. Probably you want to remove "Uma Thurman". If you want to keep that as default name for all objects where name is not specified at initialization time, you would want to add that in the constructor. *
public class RoseDS4L2Person
{
// other lines ....
RoseDS4L2Person(String name, int age) {
this.Age = age;
this.name = name;
}
}
*
Something like this:
public class RoseDS4L2Person
{
private static final String UMA_THURMAN = "Uma Thurman";
// other lines ....
RoseDS4L2Person( int age) {
this.Age = age;
this.name = UMA_THURMAN;
}
}
The error is popping up because you have created objects with a non-existing constructor.Making objects with the default constructor or creating a constructor
which can accept the arguments you pass should do the trick.
Happy Coding

I can't seem to figure out what to do with this instance so that my code could print out the requirement

So the specifications are: Create a BankAccount class. It should contain the following information, stored in instance variables.
I need to have a constructor: BankAccount(String firstName, String lastName, double openingBalance). And a public String firstName(), a public String lastName(), and a public double balance() that return the First Name, last name and balance respectively.
And I have this so far...
public class BankAccountAssignmentPart1 {
private String firstName;
private String lastName;
private double openBalance;
BankAccountAssignmentPart1 (String firstName, String lastName, double openBalance) {
firstName = "Alfred";
lastName = "Jones";
openBalance = 1408;
}
public String firstName() {
return firstName;
}
public String lastName(){
return lastName;
}
public double Balance(){
return openBalance;
}
public static void main(String[] args){
BankAccountAssignmentPart1 m = new BankAccountAssignmentPart1();
System.out.println(m.firstName());
System.out.println(m.lastName());
System.out.println(m.Balance());
}
}
So the problem I have is in the line BankAccountAssignmentPart1 m = new BankAccountAssignmentPart1(); in Eclipse it says that the constructor is undefined and goes on to give suggestions to change the code such as removing the String String double or change the modifier to static which can't happen in instances....So I don't know what to do.
Please Help!
You need to specify parameters when you call your constructor:
BankAccountAssignmentPart1 m = new BankAccountAssignmentPart1("1","2",0);
Otherwise it tries to find BankAccountAssignmentPart1() constructor (with no parameters), which is indeed undefined.

Categories

Resources