Constructor printing out NULL instead of object value - java

I created a new class "Lecturer" which extends another class "Person", i wanted to make 2 constructors for Lecturer and one would accept a name and a stipend (just a constant to say how much pay is), the other just accepts the name and uses the default stipend set in the code. i included appropriate getters and setters. I then wrote a writeOutput method to print an output similar to this
Name: (name) which gets the name and prints it
Stipend: (stipend) same process ^
heres what i have so far
Lecturer.java
public class Lecturer extends Person{
private static String name;
static double stipend;
public Lecturer(String name) {
super(name);
}
public Lecturer(String name, double stipend) {
super(name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getStipend() {
return stipend;
}
public void setStipend(double stipend) {
this.stipend = stipend;
}
public static void writeOutput() {
System.out.println("Name: " + name);
System.out.println("Stipend: " + stipend);
}
}
Person.java
public class Person {
/** Every Person has a name */
private String name;
/** Person requires a name */
public Person(String n) {
this.name = n;
}
/** return this Person's name */
public String getName() {
return this.name;
}
/** Change this Person's name */
public void setName(String nn) {
this.name = nn;
}
Main file (Inheritance.java)
Lines 41-53
Lecturer l1 = new Lecturer("Zachary");
Lecturer l2 = new Lecturer("Wilhelmina", 11017.00);
l1.writeOutput();
l2.writeOutput();
pause();
l1.setName("Zack");
l1.setStipend(10800.00);
l1.writeOutput();
pause();
System.out.printf("%s's stipend is $%,4.2f.\n",
l1.getName(), l1.getStipend());
System.out.printf("%s's stipend is $%,4.2f.\n",
l2.getName(), l2.getStipend());
This is the output
Name: null
Stipend: 0.0
Name: null
Stipend: 0.0
press enter...
Name: Zack
Stipend: 10800.0
The 2nd part works as it should but the first one isnt and i tried to change the code but nothing is working properly.

In Lecturer you are declaring another name variable. This variable is separate from the name variable declared in Person. The call to the superclass constructor is setting the name variable in Person, not in Lecturer. But you don't need the second variable; remove it. You can access the name in Person via the getName method you've already declared. This means that you also don't need to re-declare getName and setName in Lecturer, so the Lecturer class can inherit them.
Also, in Lecturer, the two variables you've declared shouldn't be static. Per the above reasoning, name shouldn't even be there, but even if it should be there, it shouldn't be static. The variable stipend should be there, but it shouldn't be static. When you declare a member variable static, then there is only one variable for the entire class, no matter how many instances you create, which doesn't sound like what you want.
Your constructors should initialize stipend.

You have a static variable inside Lecturer which has the same name as the inherited one from Person and your getter is referring to that static one - are you sure you want these static variables? For completeness if you really want to keep the static one and the inherited one with the same name then change your getter to read return this.name; which will return the inherited name instance variable.... But that method can be inherited from Person class...

There are two name fields in your program , one is private static String name; in Lecturer.java and another is private String name; in person.java .
The thing is that you are just calling Lecturer javs's name field but not setting it.

Fixed the project based on rgettman answer.
Lecturer class should look like this:
public class Lecturer extends Person {
double stipend = 9144;
public Lecturer(String n) {
super(n);
}
public Lecturer(String n, double stipend) {
super(n);
this.stipend = stipend;
}
public double getStipend() {
return stipend;
}
public void setStipend(double stipend) {
this.stipend = stipend;
}
public void writeOutput() {
System.out.println("Name: " + this.getName());
System.out.println("Stipend: " + getStipend());
}
}

Related

JAVA: Proper way to use superclass' getter and setter in subclass

I have a class Person and its subclass Student:
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Student extends Person {
private int grade;
public Student(String name, int grade) {
super(name);
this.grade = grade;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
public void printDescription() {
System.out.println("Name: " + getName());
System.out.println("Grade: " + Integer.toString(grade));
}
}
So Person have getter and setter for name property and Student have only getter and setter for its new grade property, as long as a printDescription() method.
The problem is how should I call the name property in Student's printDescription() method correctly?
I implemented it like in code above considering that Student inherits getter and setter from parent class.
But at my university Java teacher asks to use it like this:
public void printDescription() {
System.out.println("Name: " + super.getName());
System.out.println("Grade: " + Integer.toString(grade));
}
So he offers to directly call parent's getter.
I think it is not the best way because in case we override name's getter in Student class, getter from Person will still be called instead.
So what approach is best in this situation to use name property?
UPD: it is important to mention that for this task there is no requirement to call specifically superclass' getter implementation, this is why I was confused by teacher's recommendation to use super.
You're correct that if you override the method in the subclass and you're using the super keyword then you'll invoke the method on the parent class.
In this case unless you wanted to guarantee that the method in the parent class was used then it's fine to just invoke the method without the super keyword and that way if you override the method then you get the behaviour you want in the subclass.
if you extends a class , it will has all properties in its superclass. instead of calling super.getName() you can just call this.getName().

java - sending variables through nested classes

I have a class that has a variable of type Name.
public class Holder {
private Name name;
private int snumber;
The Name class has two strings called first and last that are assigned values by setter methods. I would like to send over the strings from the Name class to name in the Holder class, but I'm having trouble doing so. I think I've taken a step in the right direction by doing this
public class Holder {
private Name name;
private int snumber;
public void setName(){
name = new Name();
name.getFirst();
name.getLast();
}
but I can't say that I really know what the correct approach is. I also tried name.setFirst(getFirst) but that doesn't work. Any ideas would be appreciated.
The same way you would if the class wasn't nested.
Your setName() method should take a parameter (maybe 2, first and last) and then invoke the name.setFirstName(), name.setLastName() methods.
Right now, your setName() method isn't doing anything.
E.G:
public class Holder
{
private Name name;
private int snumber;
public Holder()
{
this.name = new Name();
}
public void setName(String firstName, String lastName)
{
this.name.setFirst(firstName);
this.name.setLAst(lastName);
}
}
Here is a good article explaining the relationship between Java inner and outer classes:
https://www.tutorialspoint.com/java/java_innerclasses.htm
class Outer_Demo {
// private variable of the outer class
private int num = 175;
// inner class
public class Inner_Demo {
public int getNum() {
System.out.println("This is the getnum method of the inner class");
return num;
}
}
}
public class My_class2 {
public static void main(String args[]) {
// Instantiating the outer class
Outer_Demo outer = new Outer_Demo();
// Instantiating the inner class
Outer_Demo.Inner_Demo inner = outer.new Inner_Demo();
System.out.println(inner.getNum());
}
}
Note that the example creates instances of both "Outer_Demo" AND "Inner_Demo (outer.new Inner_Demo();).
Ok, so I figured something out that works.
public class Holder {
private int snumber;
private Name name;
public void setName(Name n){
name=n;
}
public Name getName(){
return name;
}

How to return a String in an inherited class?

So I have created a superclass called "Food" which takes a String called "name" as a parameter, I now want to created an inherited class called "Meat" and give that class the name of "Meat" which it inherits from the Food class. Here is my current attempt:
public class Meat extends Food
{
public Meat(String name) {
String meat = name;
}
public String getName() {
return name;
}
}
Here is the Food class:
public class Food {
//field that stores the name of the food
public String name;
//constructor that takes the name of the food as an argument
public Food(String name){
this.name = name;
}
public String getName() {
return name;
}
}
I'm not currently sure how to write out the Meat constructor to assign the name. Any help is appreciated, thanks.
You need to call the super constructor from the child constructor:
public class Meat extends Food {
public Meat(String name) {
super(name);
}
}
Read the tutorial about super.
I don't see the added value of having the Meat class, unless you override methods or add fields or methods. You could just define your meat as Food:
Food meat = new Food("Meat");
But if you do extend the Food class, your Meat class will have to call one of Food's constructors. The easiest way to do that is by having a Constructor with the same signature:
public Meat(String food){
super(food);
}
Note that every Java class has a constructor. If you don't define one explicitly, the compiler inserts a constructor with public visibility and without parameters.
You won't need to do anything else with the getName().
In the Meat class you can create the constructor like this:
public Meat(String name) {
super(name);
}
But if you want to override it then you can do something like this:
#Override
public String getName() {
String name = "Meat" + this.name;
return name;
}
If I understand correctly, you want all your Meat objects to have "Meat" as name. You should do this:
public class Meat extends Food {
public Meat() {
super("Meat");
}
}

Not figuring out how the static variable is working in this case

I am trying to understand how the static variables work so apologies in advance if this question is basic.
I have a class Employee which has 2 public static variables both of type String and initial value null.
public class Employee {
public static String FIRST_NAME = null;
public static String LAST_NAME = null;
}
I have another class Job which has 1 public static variable of type Employee and initial value null.
public class Job {
public static Employee EMPLOYEE = null;
}
I create a separate class to print out the initial values.
public class Testing {
public static void main(String[] args) {
System.out.println("Employee.FIRST_NAME=" + Employee.FIRST_NAME);
System.out.println("Employee.LAST_NAME=" + Employee.LAST_NAME);
System.out.println("Job.EMPLOYEE=" + Job.EMPLOYEE);
System.out.println("Job.EMPLOYEE.FIRST_NAME=" + Job.EMPLOYEE.FIRST_NAME);
System.out.println("Job.EMPLOYEE.LAST_NAME=" + Job.EMPLOYEE.LAST_NAME);
}
}
And this was the output:
Employee.FIRST_NAME=null
Employee.LAST_NAME=null
Job.EMPLOYEE=null
Job.Employee.FIRST_NAME=null
Job.Employee.LAST_NAME=null
Then I assign values to static variables of Employee class. And then I print out all the values of both classes again.
public class Testing {
public static void main(String[] args) {
Employee.FIRST_NAME = "John";
Employee.LAST_NAME = "Doe";
System.out.println("Employee.FIRST_NAME=" + Employee.FIRST_NAME);
System.out.println("Employee.LAST_NAME=" + Employee.LAST_NAME);
System.out.println("Job.EMPLOYEE=" + Job.EMPLOYEE);
System.out.println("Job.EMPLOYEE.FIRST_NAME=" + Job.EMPLOYEE.FIRST_NAME);
System.out.println("Job.EMPLOYEE.LAST_NAME=" + Job.EMPLOYEE.LAST_NAME);
}
}
And this was the output:
Employee.FIRST_NAME=John
Employee.LAST_NAME=Doe
Job.EMPLOYEE=null
Job.Employee.FIRST_NAME=John
Job.Employee.LAST_NAME=Doe
Why Job.EMPLOYEE is null?
Thanks for reading my question.
I hope the code was only an example. If not: you shouldn't use static variables this way, since they are global for all instances of the class in the same runtime (it's actually one variable for all instances of the class/subclasses). Job.EMPLOYEE is still null because you haven't assigned a value to it.
Static variables are initialized the first time you access a class in your code. Here's the flow:
-Main method runs and starts at first line
-The employee class has its first name and last name variables set
-The first and second print line statements access those variables
-The employee variable is not set, so the value is null
-The Job.EMPLOYEE is null, but by calling the static variable you are calling Employee.FIRST_NAME which is static so it returns the static variable on the Employee class (not recommended as many others stated very clearly.) You may have expected a NullReferenceException, but the call you are making is on the class and not the instance.
Hope that helps!
The variables in your classes should not be static. static means that there will only be one value for all instances of that class. i.e. each instance will have the same value.
You should make the variables non-static (just remove the static keyword).
You should also make them private and provide accessor methods to them such as getters and setters. You can also create a constructor that accepts a first name and last name which will create objects of the class for you.
For example:
public class Employee {
private String firstName = null;
private String lastName = null;
public Employee(String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getLastName()
{
return lastName ;
}
public void setLastName(String lastName)
{
this.lastName = lastName ;
}
}
You can then create Employee objects like this:
Employee employee1 = new Employee("Joe", "Bloggs");
Employee employee2 = new Employee("John", "Smith");
You can access the object's variables like this:
System.out.println("Employee 1 first name: " + employee1.getFirstName());
System.out.println("Employee 1 last name: " + employee1.getLastName());
You can edit the object's variables like this:
employee1.setFirstName("Adam");
Then do the same for the Job class and use the Job classes setEmployee method to set a Job object's Employee variable equal to an Employee object that you have created.

Use of "this" keyword in java [duplicate]

This question already has answers here:
What is the meaning of "this" in Java?
(22 answers)
Closed 7 years ago.
I was studying method overriding in Java when ai came across the this keyword. After searching much about this on the Internet and other sources, I concluded that thethis keyword is used when the name of an instance variables is same to the constructor function
parameters. Am I right or wrong?
this is an alias or a name for the current instance inside the instance. It is useful for disambiguating instance variables from locals (including parameters), but it can be used by itself to simply refer to member variables and methods, invoke other constructor overloads, or simply to refer to the instance. Some examples of applicable uses (not exhaustive):
class Foo
{
private int bar;
public Foo() {
this(42); // invoke parameterized constructor
}
public Foo(int bar) {
this.bar = bar; // disambiguate
}
public void frob() {
this.baz(); // used "just because"
}
private void baz() {
System.out.println("whatever");
}
}
this keyword can be used for (It cannot be used with static methods):
To get reference of an object through which that method is called within it(instance method).
To avoid field shadowed by a method or constructor parameter.
To invoke constructor of same class.
In case of method overridden, this is used to invoke method of current class.
To make reference to an inner class. e.g ClassName.this
To create an object of inner class e.g enclosingObjectReference.new EnclosedClass
You are right, but this is only a usage scenario, not a definition. The this keyword refers to the "current object". It is mostly used so that an object can pass itself as a parameter to a method of another object.
So, for example, if there is an object called Person, and an object called PersonSaver, and you invoke Person.SaveYourself(), then Person might just do the following: PersonSaver.Save( this );
Now, it just so happens that this can also be used to disambiguate between instance data and parameters to the constructor or to methods, if they happen to be identical.
this keyword have following uses
1.used to refer current class instance variable
class Student{
int id;
String name;
student(int id,String name){
this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
s1.display();
s2.display();
}
}
here parameter and instance variable are same that is why we are using this
2.used to invoke current class constructor
class Student{
int id;
String name;
Student (){System.out.println("default constructor is invoked");}
Student(int id,String name){
this ();//it is used to invoked current class constructor.
this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student e1 = new Student(111,"karan");
Student e2 = new Student(222,"Aryan");
e1.display();
e2.display();
}
}
3.this keyword can be used to invoke current class method (implicitly)
4.this can be passed argument in the method call
5.this can be passed argument in the constructor call
6.this can also be used to return the current class instance
This refers current object. If you have class with variables int A and a method xyz part of the class has int A, just to differentiate which 'A' you are referring, you will use this.A. This is one example case only.
public class Test
{
int a;
public void testMethod(int a)
{
this.a = a;
//Here this.a is variable 'a' of this instance. parameter 'a' is parameter.
}
}
Generally the usage of 'this' is reserved for instance variables and methods, not class methods ...
"class methods cannot use the this keyword as there is no instance for
this to refer to..."
http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
Here's a trivial example ...
public class Person {
private String name;
private int age;
private double weight;
private String height;
private String gender;
private String race;
public void setName( String name ) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setAge( int age) {
this.age = age;
}
public int getAge(){
return this.age;
}
public void setWeight( double weight) {
this.weight = weight;
}
public double getWeight() {
return this.weight;
}
public void setHeight( String height ) {
this.height = height;
}
public String getHeight() {
return this.height;
}
public void setGender( String gender) {
this.gender = gender;
}
public String getGender() {
return this.gender;
}
public void setRace( String race) {
this.race = race;
}
public String getRace() {
return this.race;
}
public void displayPerson() {
System.out.println( "This persons name is :" + this.getName() );
System.out.println( "This persons age is :" + this.getAge() );
System.out.println( "This persons weight is :" + this.getWeight() );
System.out.println( "This persons height is :" + this.getHeight() );
System.out.println( "This persons Gender is :" + this.getGender() );
System.out.println( "This persons race is :" + this.getRace() );
}
}
And for an instance of a person ....
public class PersonTest {
public static void main( String... args ) {
Person me = new Person();
me.setName( "My Name" );
me.setAge( 42 );
me.setWeight( 185.00 );
me.setHeight( "6'0" );
me.setGender( "Male" );
me.setRace( "Caucasian" );
me.displayPerson();
}
}
In case of member variable and local variable name conflict, this key word can be used to refer member variable like,
public Loan(String type, double interest){
this.type = type;
this.interest = interest;
}
if you have knowladge about c,c++ or pointers, in that language this is a pointer that points object itself. In java everything is reference. So it is reference to itself in java. One of the needs of this keyword is that:
Think that this is your class
public class MyClass
{
public int myVar;
public int myMethod(int myVar)
{
this.myVar = myVar; // fields is set by parameter
}
}
If there is not this keyword you it is confused that this is paramter or class field.When you use this.myVar it refers field of this object.
I would like to modify your language. The this keyword is used when you need to use class global variable in the constructors.
public class demo{
String name;
public void setName(String name){
this.name = name; //This should be first statement of method.
}
}
this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
One more thing that should be in mind is that this keyword might be the first statement of your method.
This is used in java. We can use in inheritance & also use in method overloading & method overriding. Because the actual parameter or instance variable name has same name then we can used this keyword complsary . But some times this is not same as when we can not use this keyword complsary.....
Eg:- class super
{
int x;
super(int x)
{
this.x=x
}
}

Categories