Minor issue when working with extended classes in Java - java

edit: this was entirely my error, likely due to rushing things at 4am. The code was technically sound and working fine, though thank to the comments I have removed some redundancy to make things a bit smarter.
I'm working on a class project that deals with Java super/subclasses and inheritance. While 90% of the code works just fine, one minor thing doesn't seem to want to work and I'm a bit perplexed as to why. Basically, we're creating a new class called CompactDisc that contains information such as product code, Description, Price, and Artist. When the user enters the appropriate code (sgtp), the console will output the information. Unfortunately the Artist line is always blank, despite giving it data. While there are other classes involved with this project, I'll will only post the ones I feel are important.
ProductApp.java:
import java.util.Scanner;
public class ProductApp
{
public static void main(String args[])
{
// display a weclome message
System.out.println("Welcome to the Product Selector\n");
// perform 1 or more selections
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
System.out.print("Enter product code: ");
String productCode = sc.next(); // read the product code
sc.nextLine(); // discard any other data entered on the line
// get the Product object
Product p = ProductDB.getProduct(productCode);
// display the output
System.out.println();
if (p != null)
System.out.println(p.toString());
else
System.out.println("No product matches this product code.\n");
System.out.println("Product count: " + Product.getCount() + "\n");
// see if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.nextLine();
System.out.println();
}
}
}
Product.java:
import java.text.NumberFormat;
public class Product
{
private String code;
private String description;
private String artist;
private double price;
protected static int count = 0;
public Product()
{
code = "";
description = "";
price = 0;
}
public void setCode(String code)
{
this.code = code;
}
public String getCode(){
return code;
}
public void setArtist(String artist)
{
this.artist = artist;
}
public String getArtist(){
return artist;
}
public void setDescription(String description)
{
this.description = description;
}
public String getDescription()
{
return description;
}
public void setPrice(double price)
{
this.price = price;
}
public double getPrice()
{
return price;
}
public String getFormattedPrice()
{
NumberFormat currency = NumberFormat.getCurrencyInstance();
return currency.format(price);
}
#Override
public String toString()
{
return "Code: " + code + "\n" +
"Description: " + description + "\n" +
"Price: " + this.getFormattedPrice() + "\n";
}
public static int getCount()
{
return count;
}
}
CompactDisc.java:
public class CompactDisc extends Product
{
private String artist;
public CompactDisc()
{
super();
artist = "";
count++;
}
#Override
public void setArtist(String artist)
{
this.artist = artist;
}
#Override
public String getArtist(){
return artist;
}
#Override
public String toString()
{
return super.toString() +
"Artist: " + artist + "\n";
}
}
ProductDB.java:
public class ProductDB
{
public static Product getProduct(String productCode)
{
// In a more realistic application, this code would
// get the data for the product from a file or database
// For now, this code just uses if/else statements
// to return the correct product data
Product p = null;
if (productCode.equalsIgnoreCase("java") ||
productCode.equalsIgnoreCase("jsps") ||
productCode.equalsIgnoreCase("mcb2"))
{
Book b = new Book();
if (productCode.equalsIgnoreCase("java"))
{
b.setCode(productCode);
b.setDescription("Murach's Beginning Java");
b.setPrice(49.50);
b.setAuthor("Andrea Steelman");
}
else if (productCode.equalsIgnoreCase("jsps"))
{
b.setCode(productCode);
b.setDescription("Murach's Java Servlets and JSP");
b.setPrice(49.50);
b.setAuthor("Andrea Steelman");
}
else if (productCode.equalsIgnoreCase("mcb2"))
{
b.setCode(productCode);
b.setDescription("Murach's Mainframe COBOL");
b.setPrice(59.50);
b.setAuthor("Mike Murach");
}
p = b; // set Product object equal to the Book object
}
else if (productCode.equalsIgnoreCase("txtp"))
{
Software s = new Software();
s.setCode("txtp");
s.setDescription("TextPad");
s.setPrice(27.00);
s.setVersion("4.7.3");
p = s; // set Product object equal to the Software object
}
else if (productCode.equalsIgnoreCase("sgtp"))
{
CompactDisc c = new CompactDisc();
c.setCode("sgtp");
c.setDescription("Sgt. Pepper's Lonely Hearts Club Band");
c.setPrice(15.00);
c.setArtist("The Beatles");
p = c; // set Product object equal to the CompactDisc object
}
return p;
}
And the output. As you can see Artist is empty:
Welcome to the Product Selector
Enter product code: sgtp
Code: sgtp
Description: Sgt. Pepper's Lonely Hearts Club Band
Price: $15.00
Artist:
Product count: 1
Continue? (y/n):
I have a hunch I did something wrong in ProductDB.java, but I could be wrong. Thanks in advance.

I cannot reproduce your error. I get the result:
Welcome to the Product Selector
Enter product code: sgtp
Code: sgtp
Description: Sgt. Pepper's Lonely Hearts Club Band
Price: 15,00 €
Artist: The Beatles
Product count: 1
Continue? (y/n):
The artist field of Product is hidden by the CompactDisk one. You should really change it to have a reasonable design. But I don't see why this shouldn't work.

Your problem exists because of the declaration
Product p
and later became
Product p = new CompactDisc();
That line means, your variables still refer to type Product and the methods from CompactDisc
Change
#Override
public String toString()
{
return super.toString() +
"Artist: " + artist + "\n";
}
to
#Override
public String toString()
{
return super.toString() +
"Artist: " + this.getArtist() + "\n";
}
When you are printing a varaible it still points to the LHS of the declaration and when you access a method it belongs to RHS.
As a side note, you have a design issues (commented the same earlier) as well by having multiple artist variables in parent and aswell as child. remove that at one level and make your program more clear.

There really shouldn't be an artist field nor a setArtist() in Product.
What happens here is that you can override a method, but you can't override a field, just hide it. And when you access fields, it depends on the type of reference, not on the actual class of the object. Since there is nothing in the artist field that was hidden by CompactDisk when you constructed it, you're getting an empty field.

Since p is a Product which has an artist field, when you call the toString method you are getting the value which is contained in his artist field, which is the empty string.
This happens primarily because you can't override a field. You are hiding the child field with the parent field.
Within the subclass, the field in the superclass cannot be referenced by its simple name, same is true for the parent class.
Since you are not using artist in Product in strange ways, I suggest to get rid of it in the Product class and use the CompactDisk one.

Related

Java if/else statement

I am working on my final project in a computer class and am trying to implement a basic if/else statement in a nested class but it is only opting to use the else case.
import java.util.Scanner;
public class CollegeApplication {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//create object by default constructor
College c1 = new College();
//create object by overloaded constructor
College c2 = new College("Frostburg", "Frostburg", "MD", 5142);
College c3 = new College("UMBC", "Baltimore", "MD", 14000);
//set the information of object 1
c1.setName("Full Sail");
c1.setCity("Winter Park");
c1.setState("FL");
c1.setStudent_Body(19285);
System.out.println("Enter your states two-letter abbreviation");
String user_State = scan.nextLine();
c1.printCollege();
System.out.println();
c2.printCollege();
System.out.println();
c3.printCollege();
}
}
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
import java.util.Scanner;
public class College {
// private data members
private String name;
private String city;
private String state;
private int student_Body;
private String tuition;
private String user_State;
// default constructor which set the data member to default value
public College() {
this.name = "";
this.city = "";
this.state = "";
this.student_Body = 0;
this.tuition = "";
this.user_State = "";
}
// parameterized constructor
public College(String name, String city, String state, int student_Body) {
super();
this.name = name;
this.city = city;
this.state = state;
this.student_Body = student_Body;
}
// getter and setter
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getStudent_Body() {
return student_Body;
}
public void setStudent_Body(int student_Body) {
this.student_Body = student_Body;
}
// print college data
public void printCollege() {
System.out.println("Name of College: " + name);
System.out.println("City of Collge: " + city);
System.out.println("State of Collge: " + state);
System.out.println("Student Body Count: " + student_Body);
this.user_State = user_State;
if (state.equals(user_State)) {
this.tuition = "Eligible";
}
else {
this.tuition = "Ineligible";
}
System.out.println("In-State Tuition: " + tuition);
}
}
If anyone could help id be greatly appreciative in knowing how to alter the if statement to not only print ineligible
This question does not contain a question but I see the problem area.
Ask yourself why your College has both a state and a user_State. Why would this class have an aspect of itself be a user_State? There isn't even a getter and setter for it (as there shouldn't be).
public void printCollege() {
this.user_State = user_State;
if (state.equals(user_State)) {
this.tuition = "Eligible";
}
else {
this.tuition = "Ineligible";
}
System.out.println("In-State Tuition: " + tuition);
}
This function takes no input and gives no output, but has side-effects of printing something and modifying fields.
The only other time user_State is referenced in College is when it's set to the empty string.
this.user_State = "";
And that's only when a College object is constructed with the default constructor. If a College object is made using the argument constructor, user_State remains null.
Anyway, this method begins by setting this empty string (or null) to itself:
this.user_State = user_State;
So it's just going to be the empty string (or null).
Next it compares the strings state with the empty string or null in user_State.
if (state.equals(user_State)) {
state is not equal to the empty string nor null in any of your test cases, so it continues to the else clause:
else {
this.tuition = "Ineligible";
}
What you probably intend is for printCollege() to take the user_State variable you asked the user for. In which case it does not take 0 arguments, it takes 1 string argument.
public void printCollege(String userState) {
if (state.equals(userState)) {
this.tuition = "Eligible";
}
else {
this.tuition = "Ineligible";
}
System.out.println("In-State Tuition: " + tuition);
}
and the invocations of printCollege(String userState) should be done as appropriate, with the input you received from the user.
Please follow Java naming conventions in the future, something like user_State should just be userState.
there is no setter method for user_State instance variable
no parameter provided for initialization of user_State instance variable
so if condition fails as it considers user_State variable as instance variable it will always be "" in case of default constructor and "null" in case of parameterized constructor
either
provide parameter to printCollege() method according to #PatricChen
or
remove the statement this.user_State = user_State from
printCollege() and provide setter method for user_State variable and
a user_State parameter to parameterized constructor of College class

How to change array to an object class?

I have cut out the code to shorten the page but I'm asking how do I change personInterests into its own class. Apologies for the vague question but essentially I want to change personInterests in my Person class to a class where personInterests has multiple variables.
import java.util.ArrayList;
import java.util.*;
public class Person{
private String personName;
private String[] personInterests = new String[3];
public Person(String personName, String[] personInterests){
this.personName = personName;
this.personInterests = personInterests;
}
public void setInterests(String[] personInterests){
this.personInterests = personInterests;
}
public String[] getInterests(){
return personInterests;
}
public String getName(){
return personName;
}
public String toString(){
String result = getName() + " ";
for (String interests : personInterests) {
result += interests + " ";
}
return result;
}
}
This was my idea of how it would work just not sure how I would use this class and call it later on.
import java.util.ArrayList;
import java.util.*;
public class Interests {
private int interestDangerRating;
private String interestName;
private ArrayList<Interests> interestsList = new ArrayList<>();
public Interests (int interestDangerRating ,String interestName){
this.interestDangerRating = interestDangerRating;
this.interestName = interestName;
}
public void addInterests(Interests p){
interestsList.add(p);
}
Interests getInterests(int i){
return interestsList.get(i);
}
}
Any help is appreciated, as I said this code has mostly been taken out and this was an old project already completed just wanted to see if I could change some of the features.
OK so here's what I would do to clean this up for you and make it work. Firstly, think about what you are trying to do. You want to create a Person who has multiple Interests, right? So the Interest class, going by your above example, can be changed to be a typical Java object class as follows:
public class Interest {
private int dangerRating;
private String name;
public Interest (int dangerRating, String name) {
this.dangerRating = dangerRating;
this.name = name;
}
public int getDangerRating() {
return dangerRating;
}
public String getName() {
return name;
}
}
So now we've an Interest class set up where you can set a name for your interest and a danger rating. What we need to do, now, is edit your Person class so as you can store a list of interests for each Person you create.
import java.util.ArrayList;
public class Person{
private String name;
private ArrayList<Interest> interests = new ArrayList<Interest>();
public Person(String name, ArrayList<Interest> interests) {
this.name = name;
this.interests = interests;
}
public void addInterest(Interest newInterest) {
interests.add(newInterest);
}
public Interest getInterest(int indexOfInterest) {
return interests.get(indexOfInterest);
}
public ArrayList<Interest> getInterests() {
return interests;
}
public String getName() {
return name;
}
public String toString() {
String result = getName() + " ";
for(Interest interest : interests) {
result += interest.getName() + "(" + interest.getDangerRating() + ")" + " ";
}
return result.trim();
}
}
This allows you to set an initial list of all interests for your new Person and, from there, you can add new interests, get all interests or get any individual interest.
Hope this helps to clarify for you how this should all fit together!
So now it's time to instantiate everything. Lets create some Interestobjects which we will use:
Interest golf = new Interest(1, "golf");
Interest swimming = new Interest(3, "swimming");
Now lets assume we want two people called John and Mary. John likes golf and swimming while Mary only likes swimming. We'd then create their list of Interest as follows:
ArrayList<Interest> johnsInterests = new ArrayList<Interest>();
johnsInterests.add(golf);
johnsInterests.add(swimming);
ArrayList<Interest> marysInterests = new ArrayList<Interest>();
marysInterests.add(swimming);
And finally, we'd then create our two Person objects which will include the persons name and interests list.
Person john = new Person("John", johnsInterests);
Person mary = new Person("Mary", marysInterests);
And voila!
First, make an Interestclass:
public class Interest {
private int interestDangerRating;
private String interestName;
// .. getters and setters
}
then in the Personclass get rid of private String[] personInterests = new String[3];
and replace it by:
private ArrayList<Interest> interestsList = new ArrayList<>();
You're getting there with the logic of your Interests class, but it needs a few changes
import java.util.ArrayList;
import java.util.*;
public class Interests {
private int interestDangerRating;
// Is this a unique name for the entire class? If yes then no worries, but if not
// then its not needed, you've already got a list of interest names below
private String interestName;
// Change the array list to hold Strings, it's a list of words
private ArrayList<String> interestsList = new ArrayList<>();
public Interests (int interestDangerRating ,String interestName){
this.interestDangerRating = interestDangerRating;
this.interestName = interestName;
}
public void addInterest(String p){ // Again, change this to String
interestsList.add(p);
}
String getInterest(int i){ // Change this to return a String, since we changed the ArrayList above
return interestsList.get(i);
}
}
There's alot more you need to think about with this class too. How do you know how many interests are in the list, should there be a length variable? Or what about a method that returns the entire list of interests rather than just 1?
Also, there's only one interestDangerRating being set in this class; if each interest has a different danger rating, should't you be adding a danger rating for every interest?
In terms of accessing your new class, you'll need to create a class in your code by:
Interests variableName = new Interests(1, "football");
I have randomly chosen '1' and 'football' above, since they are in your Interest class' constructor. The way your class is built, you cannot use it without providing an int and a String when the object is made
Finally, to call methods on your class, you use the variable created above to call its methods:
variableName.addInterest("basketball");
String interest = variableName.getInterest(1);
If you're struggling, I recommend looking at a simple java tutorial online. instatiating java classes and calling their methods like this are fundamental concepts in Java :)

toString method

I want to add a toString method in the Item class that returns the title of the item in there.
I have need make sure that the toString method in the DVD class calls the toString method in Item so that it can return a string that contains both the title and the director.
Item is the superclass and DVD is the subclass.
public class Item
{
private String title;
private int playingTime;
private boolean gotIt;
private String comment;
public Item(String theTitle, int time)
{
title = theTitle;
playingTime = time;
gotIt = false;
comment = "<no comment>";
}
// Getters and setters omitted
public void print()
{
System.out.print(title + " (" + playingTime + " mins)");
if(gotIt) {
System.out.println("*");
} else {
System.out.println();
}
System.out.println(" " + comment);
}
}
public class DVD extends Item
{
private String director;
public DVD(String theTitle, String theDirector, int time)
{
super(theTitle, time);
director = theDirector;
}
// Getters and setters omitted
public void print()
{
System.out.println(" director: " + director);
}
}
Item toString:
public String toString()
{
return title;
}
DVD toString:
public String toString()
{
return super.toString() + " director: " + director;
}
Also, I don't know what you're trying to do with this but I would put those print() methods in these classes.
You will be better of returning the string representation and printing it somewhere else (with this you can test this class without mocking System.out)
Cheers
A toString method is already defined in each Java class (it inherits the toString of Object). But it will return a practically meaningless value (AFAIR, the internal address/id of the instance within the JDK - I might be wrong).
What you need to do is to override that method and make it return a String that is the title of the Item. For the DVD class, you have to override toString and make it a string made up of the concatenation of the title and director.
For the Item class, your method should look something like this:
public String toString(){
return this.title;
}
You should be able to use the same idea to implement toString for DVD.

find a keyword in a collection and return it

I have a collection i added CD, DVD, book information into hashsets.
Each one has a keyword and i would like to do a search for a specific keyword and return the specific book,CD,dvd... heres the output to give you an idea..
-Book-
Author: Robert A. Heinlein
# pages 325
title: Starship Troopers
keywords: [science fiction, war, weapons]
-Music-
band: Grateful Dead
# songs: 12
members: [Jerry Garcia, Bill Kreutzman, Keith Godcheaux]
title: Europe In '72
keywords: [acid rock, sixties, jam bands]
-Movie-
director: Sofia Coppola
# scenes: 14
cast: [Bill Murray, Scarlett Johansson]
title: Lost In Translation
keywords: [Japan, loneliness]
>>> items for keyword: science fiction
none
>>> items for keyword: jam bands
none
C:\Java\a03>
I have 3 classes.
Main()
Library - this is where i do all the adding of cd, DVD, books. lookups, etc
Items class(CD class, DVd class, book class) using inheritance..
in main() i am sending in information to the library class to add to the sets.
then i print out all the books, cd, movies just added.
then i do a lookup for a specific keyword.
And this is where i am having problems. i wrote a getkeyword function in CD, DVD, book class.
What i want to do is get the keyword and then see if they match and then return it as a collection.
here is main() i will only show some of it to keep this short - i will not show you how i am adding since it works good..
printItemsForKeyword(out, "science fiction");
printItemsForKeyword(out, "jam bands");
printItemsForKeyword(out, "xxx");
private static void printItemsForKeyword (PrintStream out, String keyword)
{
Collection<Item> items;
out.printf(">>> items for keyword: %s\n\n", keyword);
items = library.itemsForKeyword(keyword);
printItems(out, items);
}
now here in the library class is where i need help
in the itemsForKeyword(String keyword) function...
so, the first thing i am trying to find is "Science Fiction"
I think i need to cast item since item has the CD, DVD, book classes and i need to return a colection???
right now i am trying to return key and it wont since its incompatable with the return.
public class Library
{
private Set<Item> theCDs = new HashSet<Item>();
private Set<Item> theDVDs = new HashSet<Item>();
private Set<Item> theBooks = new HashSet<Item>();
public Collection<Item> itemsForKeyword(String keyword)
{
Item key = new Item();
((CD)key).getKeyword(); // i dont think i am even doing this right
if(key.equals(keyword))
{
return key; // cant return key
}
return null;
}
I did define a getKeywords() function in each of the classes below.
Here is the Items class since you will need to look it over..
import java.io.PrintStream;
import java.util.Collection;
import java.util.*;
class Item
{
private String title;
public String toString()
{
String line1 = "title: " + title + "\n";
return line1;
}
public void print()
{
System.out.println(toString());
}
public Item()
{
}
public Item(String theTitle)
{
title = theTitle;
}
public String getTitle()
{
return title;
}
}
class CD extends Item
{
private String artist;
private String [] members;
private String [] keywords;
private int number;
public CD(String theTitle, String theBand, int Snumber, String... keywords)
{
super(theTitle);
this.artist = theBand;
this.number = Snumber;
this.keywords = keywords;
}
public void addband(String... member)
{
this.members = member;
}
public String getArtist()
{
return artist;
}
public String [] getMembers()
{
return members;
}
public String [] getKeyword()
{
return keywords;
}
public String toString()
{
return "-Music-" + "\n"
+ "band: " + artist + "\n"
+ "# songs: " + number + "\n"
+ "members: " + Arrays.toString(members)
+ "\n" + super.toString()
+ "keywords: " + Arrays.toString(keywords)
+ "\n" + "\n" ;
}
public void print()
{
System.out.println(toString());
}
}
class DVD extends Item
{
private String director;
private String [] cast;
private int scenes;
private String [] keywords;
public DVD(String theTitle, String theDirector, int nScenes, String... keywords)
{
super(theTitle);
this.director = theDirector;
this.scenes = nScenes;
this.keywords = keywords;
}
public void addmoviecast(String... members)
{
this.cast = members;
}
public String [] getCast()
{
return cast;
}
public String getDirector()
{
return director;
}
public String [] getKeyword()
{
return keywords;
}
public String toString()
{
return "-Movie-" + "\n"
+ "director: " + director + "\n"
+ "# scenes: " + scenes + "\n"
+ "cast: " + Arrays.toString(cast) + "\n"
+ super.toString()
+ "keywords: " + Arrays.toString(keywords)
+ "\n" + "\n" ;
}
public void print()
{
System.out.println(toString());
}
}
class Book extends Item
{
private String author;
private int pages;
private String [] keywords;
public Book(String theTitle, String theAuthor, int nPages, String... keywords)
{
super(theTitle);
this.author = theAuthor;
this.pages = nPages;
this.keywords = keywords;
}
public String getAuthor()
{
return author;
}
public String [] getKeyword()
{
return keywords;
}
public void print()
{
System.out.println(toString());
}
public String toString()
{
return "-Book-" + "\n"
+ "Author: " + author + "\n"
+ "# pages " + pages + "\n"
+ super.toString()
+ "keywords: " + Arrays.toString(keywords)
+ "\n" + "\n" ;
}
}
the reason why i think i need to do sometype of cast is because i had to when i added
bandmembers..
public void addBandMembers(Item musicCD, String... members)
{
((CD)musicCD).addband(members);
}
So, what can i do to find a keyword in the items and return those?
would it be better to look directly at the sets and do some type of cast to get it to return? im just stumped..
Thank you..
Create an index (SortedMap<String, List<Item>>) relating keywords to the items they represent. When an object is added to the library, map it to each of its keywords in the index, adding new keywords as needed. Search the index to find the objects.
It's a little hard to follow what you're trying to ask, but I hope the following is what you're after. It looks to me that you're chiefly concerned with getting a Collection of Items, which you want done using the method public Collection<Item> itemsForKeyword(String keyword).
In this method, you should do the following:
Create an empty Collection (either a HashSet or TreeSet depending on whether you need it sorted).
Loop through theCDs. For each Item, get its keywords.
Loop through keywords. If you find one that equals (or equalsIgnoreCase) the one passed in, add the Item to the Collection you created in 1.
Repeat 2 and 3 for theDVDs and theBooks.
Return the Collection you created in 1.
A couple of other things:
I'd suggest that you rename getKeyword to getKeywords, since that's what it's returning.
For the purposes of this method, you would be better off having keywords in a HashSet so that you can do item.getKeyword().containsKey(keyword) instead of the looping in 3. If you do this and need it the method to be case insensitive, you would need to store keywords in all lower case or all upper case, and add in a step 0 to convert the passed in keyword to the correct case before searching. Also, this may not be the way to go if you need to extensively use keywords as an array elsewhere.

Java program error creating a Person class

Please can anyone tell me what the error is in the following piece of code?
Question is
Create a class person which has
A variable ‘name’ which stores the name of the person.
A constructor that takes a single argument that is used to initialize the name variable
A method getName() which displays the name.
A protected method setName() that takes one argument which is used to modify the name variable.
Create a subclass of the above class called student, which contains
A variable to store PRN of a student
A variable to store course the student belongs to
A method, which displays all the details of the student i.e, name, prn and course.
Program :
class Person
{
String name;
Person(String s)
{
name=s;
}
void getName()
{
System.out.println("Name is "+name);
}
void setName(String sa)
{
name=sa;
}
}
class subPerson extends Person
{
//String sa;
int Prn;
String course;
subPerson(String s,int P,String co)
{
name=s;
Prn=P;
course=co;
}
void displayal()
{
System.out.println("Name is ");
System.out.println("PRN is "+Prn);
System.out.println("course is "+course);
}
}
class Inher
{
public static void main(String args[])
{
int area,volumea;
subPerson h1 = new subPerson("Abhishek",20,"MBA");
h1.displayal();
}
}
Person's constructor takes a String. Since subPerson extends Person, its constructor will invoke a constructor of Person. By default it'll use the no-arg constructor, but since Person doesn't have one, it won't work.
Try changing subPerson's constructor to this:
subPerson(String s,int P,String co)
{
super(s);
Prn=P;
course=co;
}
I assume that compiles (I'm not going to check that), then the fundamental problem is that in the displayal() method, you don't actually print out the name...
System.out.println("Name is ");
should actually be something like
System.out.println("Name is " + name);
Aside from that, there are some problems with not following typcial java coding conventions. While the code may compile and do what is desired, most java guys will likely get hung up on "not following naming conventions" instead of trying to fix the problem because the code looks unusual.
I'd also recommend that you pay more attention to names. They matter a great deal and deserve careful thought.
"subPerson" as a class name leaves me quite cold. Aside from the poor camel case style, the assignment explicitly calls for a class Student. Why did you go with "subPerson"?
I would advise against the "displayal" (sic) method as well. The proper idiom is to override the toString() method in Object.
I'd write it like this:
/**
* Person
* User: Michael
* Date: Sep 27, 2009
* Time: 10:00:00 AM
*/
public class Person
{
private String name;
public static void main(String[] args)
{
Person s = new Student("Foo Bar", "35", "Intro To Java");
System.out.println(s);
}
public Person(String name)
{
if ((name == null) || (name.trim().length() == 0))
throw new IllegalArgumentException("name cannot be blank or null");
this.name = name;
}
public String getName()
{
return name;
}
public void setName(String name)
{
if ((name == null) || (name.trim().length() == 0))
throw new IllegalArgumentException("name cannot be blank or null");
this.name = name;
}
#Override
public String toString()
{
return "Person{" +
"name='" + name + '\'' +
'}';
}
}
class Student extends Person
{
private String prn;
private String course;
Student(String name, String prn, String course)
{
super(name);
this.prn = prn;
this.course = course;
}
#Override
public String toString()
{
return "Student{" +
"name='" + getName() + '\'' +
", prn='" + prn + '\'' +
", course='" + course + '\'' +
'}';
}
}

Categories