Results 1 to 2 of 2
- 02-07-2011, 11:34 AM #1
Member
- Join Date
- Jan 2011
- Posts
- 93
- Rep Power
- 0
String passed as argument to a constructor returns null value
I made a program to practice inheritance which uses a GUI.
It consists of three classes for the moment:
School_School.java
Java Code:abstract public class School_School { public abstract void getName(); public abstract void printName(); }
Java Code:import javax.swing.JOptionPane; public class School_Teachers extends School_School{ private String firstName; private String lastName; private String name = firstName + " " + lastName; public School_Teachers(String firstName,String lastName) { this.firstName=firstName; this.lastName=lastName; } public School_Teachers() { getName(); } public void getName() { this.firstName = JOptionPane.showInputDialog(null, "Enter First Name: ", "Teacher | Registration", JOptionPane.OK_OPTION); this.lastName = JOptionPane.showInputDialog(null, "Enter Last Name: ", "Teacher | Registration", JOptionPane.OK_OPTION); } public void printName() { System.out.println("Name Entered: "+this.name); } }
Java Code:public class School_MainClass { public static void main(String[] args) { School_School teacher = new School_Teachers("Severus","Snape"); teacher.printName(); } }
Name entered: null null
and i dont understand why that is? Could someone please explain and tell me where i've gone wrong - thanks!
- 02-07-2011, 11:44 AM #2
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 14,422
- Blog Entries
- 7
- Rep Power
- 28
You don't initialize firstName and lastName (you can't because those names are only known when the constructor is called) so they equal null. You try to initialize the name member with those other two null values. Set the value of your name value in your constructor (after firstName and lastName have received they value) and you'r fine.
kind regards,
JosBuild a wall around Donald Trump; I'll pay for it.
Similar Threads
-
What is the Use of No argument Constructor in JAVA Beans
By JyotirmoyDeb in forum New To JavaReplies: 2Last Post: 10-16-2010, 02:44 AM -
getImplementationVersion() returns null
By newbiejava in forum New To JavaReplies: 22Last Post: 09-12-2010, 10:31 AM -
Null array when passed to MouseListener
By stevemcc in forum New To JavaReplies: 2Last Post: 04-02-2008, 11:42 PM -
How to resolve Constructor argument in Spring
By Java Tip in forum Java TipReplies: 0Last Post: 03-29-2008, 01:43 PM -
How to resolve Constructor argument in Spring
By JavaBean in forum Java TipReplies: 0Last Post: 09-26-2007, 09:34 PM
Bookmarks