What is the difference between those kind of instantiation? - java

it's maybe a newbie question but I think it will be helpful for some beginners.
My question is :
public abstract class Person {
code goes here ....
}
public class Employee extends Person {
code goes here ....
}
What is the difference between those kind of instantiation ?
Person student = new Employee("Dove","Female",0);
and
Employee student = new Employee("Dove","Female",0);

They are essentially the same, but the compiler treats Person student as a Person without any type information from the concrete class Employee

It's basically the same thing, but the difference is that:
1- In the first declaration:
Person student = new Employee("Dove","Female",0);
Here student can't access Employee class specific methods or attributes as it's a Person object which contains an Employee instance.
2- But in the second one:
Employee student = new Employee("Dove","Female",0);
Here student can benefit from both Employee and Person attributes and methods.
Please check Polymorphism Oracle Docs for further reading about polymorphism in Java.
Example:
We can see that in this example, where we use Integer and Object classes:
Integer i1= new Integer(0);
//This will run and execute perfectly
System.out.println(i1.intValue());
Object i2= new Integer(0);
//This will throw an error as `Object` class doesn't have `intValue()` method.
System.out.println(i2.intValue());
This is a live working Demo so you can see that.

Following is difference in both instantiation.
(1)
Person student = new Employee("Dove","Female",0);
In this instantiation student is object of Person class so it can't access Employee class specific methods or attributes.
(2)
Employee student = new Employee("Dove","Female",0);
Here, in second instantiation student can access Employee class specific methods and attributes as well as Person class because it is extending in Employee class.
This is basic difference in this two statements.

Related

Java Class data type [duplicate]

This question already has answers here:
How can a class have a member of its own type, isn't this infinite recursion?
(7 answers)
Closed 6 years ago.
Class Person {
Person name;
Person age;
..
}
In this usage , what does it mean Person name and Person age. Of course name and age data type is Person but I cannot understand the concept how will I use in my program.
For example
if I Person data type replaced by String name and int age , I will use in main method like:
Person p1 = new Person();
p1.name = "blabla";
p1.age = 30;
But how will we use the Person data type like that.
I have already searched on the Internet but I couldn't find anything about that.
This is a bad (catastrophic) design decision.
Instead it should look like
class Person {
String name;
int age;
}
There are possibilities when using Person within Person would be justified. Look at the following examples.
class Person {
Person manager; // Here, an employee could have another Person being its manager
}
class Person {
Person partner; // Here, a person could be married and have another Person as partner
}

Referencing objects to arraylist [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Hi I'm unsure how I go about referencing objects to my arraylist.
The class where im declaring the arraylist:
Any help would be much appreciated
First of all name is not static so you can not access it as Student.name only instance of student can access it if it's public.Now, you want to construct the Student than you should pass the name of student in constructor.You can declare getter and setter methods for your Student attributes.
Moreover ArrayList.add can be used to add your Students to your list and you better not add students in constructor use different method to write this scenario.
FOR EXAMPLE :
Student student = new Student("NewStudent");
System.out.println("Name of student :" +student.getName());
studentList.add(student);
Regarding:
public TutorGroup() {
super();
Student student = new Student(Student.name); // this makes no sense
studentList.add(student.Student(name, tmaMark));
}
I'm not sure what you're trying to do with new Student(Student.name) since it isn't clear what this code is trying to do, but regardless, the compiler is right -- it shouldn't exist, and so get rid of it.
Delete this TutorGroup constructor and re-do it. How you re-do it will depend on where your TutorGroup is to get the Student objects. If they're going to be packed into an ArrayList and then passed in, then give TutorGroup's constructor an ArrayList<Student> parameter, and when calling the class, pass in the list. If you will add Students one at a time, then make the constructor simple (or get rid of it), and give the TutorGroup class an addStudent method:
public void addStudent(Student s) {
studentList.add(s);
}
In your TutorGroup constructor your trying to pass the value in the name variable in the Student class which you cant access because 1. The name variable is private so only members of the class have access to it. and 2. It doesn't hold a value yet since that's what your trying to pass into the Student constructor.
What you should do is pass a string literal into your Student constructor like: new Student("Jamie") then it will be saved in the name variable in your Student class, and if you need to access the name later add a public method in your Student class that returns the value in your name variable.
Your code has several issues.
Firstly the Student class should have some getter methods, so that you can access the data from a student object:
public String getName() {
return this.name;
}
public int getTmaMark() {
return this.tmaMark;
}
For creating a student object with the correct data, you have 2 options:
Option A) Create a constructor for Student that takes both values:
public Student(String aName, int aMark)
{
super();
this.name = aName;
this.tmaMark = aMark;
}
Option B) Create setters for your Student class
public void setName(String aName) {
this.name = aName;
}
public void setTmaMark(int aMark) {
this.tmaMark = aMark;
}
You can, of course, implement both options in Student, giving you extra flexibility.
Then, to add a new Student to your ArrayList, you can simply create a student and use the array's add method:
Examples:
ArrayList<Student> studentList = new ArrayList<Student>();
// Create student using constructor
Student studentA = new Student("Alice", 15);
// Create student using setters
Student studentB = new Student();
studentB.setName("Bob");
studentB.setTmaMark(10);
// Add both students to the ArrayList
studentList.add(studentA);
studentList.add(studentB);
Please remeber that for the studentB example, if you added a constructor with arguments to your Student class (Option A) you also need to create an explicit default constructor (without arguments).
Im not sure exactly what you are trying to do. I am going to assume you want to add a student into the ArrayList called student list. The line Student student = new Student(Student.name); is creating a new object of type Student called student but you are not passing into any parameters into the constructor for the student class, but it requires a String which is used as the name. What you want to do (i think) is add a student to your array list. As your ArrayList has type student the method to add student x should be
public void addStudent(Student x)
{
studentList.add(x);
}
Where Student x is passed as a paramater to the addStudent method. To Create a new student with the object name newstu and the name nameOfStu you could do this.
Student newstu = new Student(nameOfStu);
addStudent(newstu);
I hope this helps.

I am getting unusual object reference codes and null values when I initialise a constructor

I have a couple of questions about how class instances are set up. If I have an object constructor as follows:
Object(String newName, ArrayList<Person> newPersonList){
name=newName;
personList=newPersonList;
System.out.println(personList);}
which is then assigned to a person as a method in the Object class:
matchPersonToObject(Person person){
this.matchedPerson=person;
person.addToObjects(this); //do I need to add the full project.domain address in here?
//Because if so it will only let me put the class `Person` in rather than an instance `person`
}
//in the person class:
addToObjects(Object obj){
this.objectList.add(obj);
System.out.println(objectList);
}
when I then initialise this as follows:
Person chris=new Person("Chris");
Object obj1=new Object("thing",new ArrayList<Person>(Arrays.asList(chris)))
it gives an output of:
[project.domain.Person#1a40fff] //personList in object constructor
[Object - null] //objectList once person has been matched to it
My two questions are
a) what is that hexidecimal code that is being give to my person instance? Why does it not just display [project.domain.chris]?
b)When I add the object to the objectList, why is this registering as null? Have I initialised the ArrayList correctly?
First: Never name your classes with reserved words of languague you are using, e.g. avoid create classes with names like Vector, Long, etc... generates confuse in your code.
Second: he hexidecimal code you are looking at is the hash code of your class Person, overwrite the method toString() os Person class.
public String toString() {
return <anything_you_want> + name;
}
it's possible a bad package importation because you have a class with Name object and compiler doesn't recognize your class, java.lang.Object is different of your Object class.

Referencing subclasses from superclasses in java

Suppose I have an abstract class Person. There is another class Student which extends Person. But the Student class has a member variable, say college of type String, which is not there in Person class.
We know that we can reference a subclass from a superclass, for example,
Person p = new Student();
Will the object p have the member college?
You won't be able to do p.college. However, you can cast it to Student and in this case it will have:
((Student) p).college;
In your sample, Person object IS a Student and hence will have the college member.
Since you cast the Student to a Person, any public routines or data not present in Person will be hidden by the cast assignment though.

I need some help designing an array

For my homework, we've been tasked with creating:
Person class with variables firstName, lastName, streetAddress, zipCode and phone.
CollegeEmployee extends Person and adds ssn, salary, and deptName.
Faculty extends CollegeEmployee by adding a boolean tenure.
Last but not least, Student extends person by adding GPA and major.
Everything looks good displaying to screen, and I'm moving on to the next part of the assignment which is to create 14 records (7 students, 4 employees and 3 faculty) in an array.
3 different classes, with multiple data types, and I cannot for the life of me figure out how to populate an array with this. This is the first array I've created that's not been completely integer. The Java Tutorials didn't give me anything, and while Java: Generic Static Multidimensional Arrays has some great information, it's a little more than I can wrap my head around right now.
I'd initially thought of creating array[14][10] -- fourteen variables each for ten objects -- but I can't mix data types. That's where I got lost.
Anyone have any suggestions on how to design this array and be able to display the values from it afterward?
Any hints and suggestions would be appreciated!
Thanks.
From what I understand, no need to get fancy with multi-dimensional arrays.
1) Create an array that takes Person instances.
Person [] myPeeps = new Person[14];
2) Create a print method on Person, which subclasses override to print the relevant info.
Because your array expects Person instances, you can put instances of any subclasses of Person, because subclasses always have an is-a relationship with their superclass.
Because Person has a print method, you can call print on anything you pull out of the array. Subclasses provide their own implementations so they can print their relevant data. That way, you don't really care about which subclass any particular instance is; the correct print implementation for the instance is invoked at runtime.
You don't need a multidimensional array. You can make an array of Person objects.
Person[] people = new Person[14];
people[0] = new Student();
people[1] = new Employee();
.
.
.
You could also create a Person[] array, just as you would an int[] array. e.g.
Person[] people = new Person[14]
You can then add people to the Array like this:
people[0] = new Student();
people[1] = new CollegeEmployee();
people[2] = new Faculty();
If you want to check what type of person is in each index you will want to use instanceof. Try looking here for more help
One example of using instanceof is:
if(people[0] instanceof Student){
System.out.println("This person is a student");
}
Or try using generics.
You could create an ArrayList<Person> and can then add any type of person to this ArrayList.
e.g.
ArrayList<Person> peopleList = new ArrayList<Person>();
//People can be added like this
peopleList.add(new Student());
peopleList.add(new CollegeEmployee();)
Again you are able to use instanceof to check which type of person is in each index!
Also if you never write
Person person1 = new Person();
In your code then consider making your class abstract.
To start:
Person[] myArray = new Person[14];
This is essentially why object oriented programming is so wonderful. If you'll notice, all Faculty, CollegeEmployee, and Student are a subset of type Person. Because of this, you can have them all contained in the same dataset if it is declared as type Person.
Person[] array = new Person[14];
You can add all of your objects to that array; however, be careful. When you go to use the elements of the array Java now only knows that each has the methods that a Person does - so therefore you can only make use of firstName, lastName, streetAddress, zipCode, and phone from these elements unless you cast the objects after they are retrieved.
Since they are all of type Person, why not use a Person array?
Person [] people = new Person[14];
You can safely add all types of Person to this array, however you can only treat them as Person (without casting). To have each subclass output customized details, and add this method in Person
class Person {
void print() {
// default Person printing
}
}
and override this method in each subclass to print its member variables:
class Student extends Person {
void print() { // <-- note same method signature!
// print "I'm a Student", GPA, major
}
}
and when the array is populated:
for (Person p : people) {
p.print(); // delegates to print method associated with the underlying type
}
Check out the inheritance tutorial
The class Person is a common superclass to all the types of the objects you want to store in the array. You can create the array based on that common supertype. Then you can access methods that are defined in that tpe on all elements of the array, regardless of the actual type -- the behavior is as defined in the actual type (look up inheritance for java if this is not clear).
If you need specific behavior based on the actual type, you need to cast the array element to the concrete type (you can determine it using instanceof, for example)

Categories