I am quite new to programming, i have a question please help me. ( this question is java question but i can't remember the syntax but what i write here is mostly it.)
A class Person speaks "i am a person"
A class Student speaks "i am a student"
Student extends from Person
Person p = new Student
then what is p speaking then?
p is just variable, it doesn't change the type of the Object that's in it.
You can think of a cup: You can put any fluid in it, but the cup won't change the type fluid.
abstract class Fluid{
public String getTemp(){
return "unknown";
}
}
class Coffee extends Fluid{
public String getTemp(){
return "hot";
}
}
class Cola extends Fluid{
public String getTemp(){
return "ice-cold"
}
}
Fluid cup = new Coffee();
System.out.println(cup.getTemp()); //It's coffe in there, so it's hot!
p is both a Student and a Person but if you call a method (like whoAreYou()), Java will first try to find it in Student and then in Person.
"I am a student"?
This is called Dynamic Binding
I think I know what you mean...
p would say he is a student, because you will override the method where the person speaks. In Java, it should look like this:
class Person
{
public void speak()
{
System.out.println("I'm a person!");
}
}
class Student extends Person
{
#Override
public void speak()
{
System.out.println("I'm a student");
}
}
"i am a student"
This is Java's polymorphism in action. The method speaks() is defined in base class Person and is overridden in the derived class Student.
In Java a base class reference can refer to a derived class object, and when a overridden method is call on such a reference, the type of the object to which the reference refers to decides the version of the method to be executed.
Even though your reference to p is declared as a Person, p is actually an instance of Student. Therefore p will "speak" whatever a student speaks.
It is legal to have refer to a Student instance as a "Person" since "Student extends from Person".
P will say student. Because Student object is casted into Person object.
Above question completely belonging to inheritance mechanism same property used by different entities.
class Person {
String identity;
Person() {
this.identity = "Person";
System.out.println("A class " + this.getClass().getName()
+ " speaks i am a " + identity);
}
}
public class Student extends Person {
public Student() {
this.identity = "Student";
System.out.println("A class " + this.getClass().getName()
+ " speaks i am a " + identity);
}
public static void main(String[] args) {
Person p = new Student();
}
}
I would guess "i am a student". This is basic polymorphism.
If the method is not static then the Student's method will be called as others mentioned. Just be careful that if the method speak is static, then the Person's method will be called. This is called hiding.
Here it is showing the concept of Polymorphism like Super class can hold the reference of child class along with that it is also showing the concept of Inheritance like Student is a Person means class Student extends Person. So here Person is a Super class and Student is a child class. As per the polymorphism Person Class (Super Class) can hold the reference of Student class (Sub-Class).
P will Speak : I am student.
But it will only have common behavior of both class. any behavior which student has but not in Person, P will not be able to access that behavior.
Person "P" is a reference here which is initialized with object of student. So when the execution of program will start, at runtime Student's class function will be called.
Here P is the Parent class Object that is holding the child class object. this is because here parent and child relationship(through inheritance ) exists because you are extending the Parent class into the Student class. Thus Parent class Object can hold the Objects of all its children class. Now P can access all the properties of its child class.
In Java when Student extends from Person you can decide what kind of behavior Student invokes from person , You can restrict student to say if it is person, You can implement it as an static then static methods are not overridden. they just shadow. If Intentionally you want instance method then you implement its specific behavior.
There is dynamic method dispatch/dynamic binding.
Person p = new Student();
p is a reference variable that type of Person which called to Student object.Student is child class and Person is parent class which extended.Two classes has methods that static or not.
Here p will speak I am a student. This is an example of dynamic binding.
This is a example of single inheritance in java.In this example,"Person" is a base class where as "Student" is a derived class.Unless anything is specified,
Person p=new Student();
object p(it seems like object of Person) will access the properties of Student class which has overriden the properties of its own base class Person.
Related
public class Test{
public static void main(String[] args){
new Person().printPerson();
new Student().printPerson();
}
}
class Student extends Person{
private String getInfo(){
return"Student";
}
}
class Person{
private String getInfo(){
return "Person";
}
public void printPerson(){
System.out.println(getInfo());
}
}
I have some questions related to Student().printPerson() in the second line of the main function.
What I know is that: Java will first try to find the printPerson() in Student class. Since it couldn't find one, it will go to find the printPerson() in the superclass of Student which is Person. Now it executes the Person's printPerson() and here are my questions:
The printPerson() invokes another method getInfo(), so which getInfo will Java choose? Could you please explain with details?
Please explain how the modifiers of the getInfo() affect the output.
For your reference, If I remembered correctly. If the modifiers of both getInfo() are public, the output will be: Person Student If they are both private, the output will be Person Person
I’m on my mobile, so forgive me for grammar and typos.
Also disclaimer, I’m not heavy with java implementation so I am giving a generic explanation and I may have a few things incorrect with how java implements.
What happens is because of access level modifiers and restricting scope.
For your person class,
You have your two methods, public print and private getInfo.
You person class can see both the methods.
Your student class you have one method, private getInfo, and you extend the person class.
Because getInfo is private, it is only know to that class and nothing else. Because of this Java will not override the super (person) getInfo with the Student’s getInfo.
Because the method is not be overridden when Student.Print is being called, student.super.print is resolving to the student.super.getInfo method instead of student.getInfo.
I have an Object named Orders. In this object, I have two parameters Vehicle and Customer.
Right now I have a method called showOrder. This method will print the type of vehicle and the customer's name.
public void showOrder() {
System.out.println("-------------------------------------------------------|Order Placed|-------------------------------------------------------");
System.out.println("The order for the car type " + vehicle.getType() + " it was place on the name " + customer.getName() + " in date of " + date);
System.out.println("----------------------------------------------------------------------------------------------------------------------------");
}
Let's say that in the future, I will add in the object Order a new Building property. How can I change this method now so that in the future, when I will add the new property, it will be possible to use it to display both Buildings and Vehicle types? Both of them will implement the Rentable interface.
The idea is that I want to make this code as generic and independent as I can...
I hope I was clear enough.
Thank you,
If I understood you correctly, you want to be able to put an object of both the Vehicle type and the Building type into the variable vehicle. For that, you could use an abstract superclass that both the Vehicle and the Building class will inherit from. It may look something like this:
public abstract class AbstractClass {
public abstract String getType();
}
The Vehicle class:
public class Vehicle extends AbstractClass {
String type;
public String getType() {
return type;
}
}
The Building class then looks very similiar:
public class Building extends AbstractClass {
String type;
public String getType() {
return type;
}
}
Now, in the Order class, you need to change the type of the variable vehicle to AbstractClass. With that, you can put an object of both the Vehicle class and the Building class into that variable. The code in your showOrder method basically stays the same as both classes you could put into the vehicle object have the method getType.
I do have class Person, class Student and Student extends Person. As far as I understood, it goes the following with static binding:
class Person {
talk(Person p) {
print("Hi by person.");
}
}
class Student extends Person {
talk(Student s) {
print("Hi by stud.");
}
}
Now if I instantiate and call method:
Person x = new Student();
talk(x);
// output: "Hi by person." because of static binding, am I right?
My Question:
What if only class Student has a method talk(Student s). Now I call talk(x). Since I usually should get talk() method from class Person, what happens when there is no such method?
EDIT: I tried to run it and it gives me an Compile Error. Ok, but why does this happen? I learned that the compiler will first go to the subclass and search for the method and if it's there, then it gets executed?
Don't exist dynamic binding for overloaded methods ...
and Student is a Person so method talk from Person invoked
class Person {
public String name;
String id;
public Person() {
System.out.println("Parent default");
name = id = "";
}
public Person(String name, String id) {
System.out.println("Parent parameter");
this.name = name;
this.id = id;
}
void show() {
System.out.println(this.name + "\n" + this.id);
}
}
class Student extends Person {
Student() {}
Student(String a, String b) {
super(a, b);
}
}
class Main {
public static void main(String args[]) {
Person p = new Person("A", "AA");
Student s = new Student("b", "BB");
s.show();
}
}
I'm very new to java, so I wanted to understand a few basic things, but I failed. If I inherit from a parent class, this means I get a copy of the parent class in the child class, right? So, in this code—if I reference the parent class' show method (in Main class), this is supposed to show the parent class' name and id which were set previously.
But it isn't showing—so I have a problem in my understanding for sure. How can I access the parent class' copy from the child class? Using the super method from child's constructor? I also want to know the basic of inheritance in short.
Consider the following statement:
Person p = new Person("A", "AA");
This is creating a Person. Its name is "A" and its id is "AA".
Now consider this statement:
Student s = new Student("b", "BB");
This is creating a new Student. It's also creating a new Person. How is that possible? Well a Student is a Person. That's what inheritance means. When a type extends another type, that is defining an "is a" relationship between the types.
Dog extends Animal, because a Dog is an Animal. Car extends Vehicle, because a Car is a Vehicle.
So when you create a new Student, you're creating a Person. Student extends Person, so a Student is a Person. Not too surprisingly, I might add.
The super keyword is used to reference a parent class' methods and fields from its child class. In your Student constructor
Student(String a, String b) {
super(a, b);
}
you're actually indirectly invoking the Person constructor by calling super(a, b). So new Student("b", "BB") creates a Person with name "b" and id "BB". That Person happens to be a Student as well.
There's no real relation whatsoever between person "a" and person "b" (though they could perhaps be distant cousins). If you ask person "a" for her name, she will reply "a". If you ask person "b" for his name, he will reply "b". It would be a little odd to have one person reply with someone else's name, so the individuals are treated as completely different people.
See also: Java Inheritance Documentation
Inheritance doesnt quite work how you think, The methods and variables are copied however the values are not.
If you make a new Person() and populate it, then make a new Student() the values in the Person are not copied, this is because values are usually based on Instances of classes not just Classes. There is a way to copy this but it is not usually done except in mistake which is to make the variable static.
Static variables are associated with the Class and not the instance and so are shared by all instances of that Class
When you call super() you are calling the method of the parent with the values of the child, so if you had two methods one overloaded and one not then you can call the parent method instead if you needed to, for instance, note it doesnt change the person class previously defined just sets the "parent" name variable in the Student
class Person{
public Person(String name) {
this.name = name;
}
}
class Student extends Person{
public Student(String name, int grade){
super(name);
this.grade = grade;
}
}
For the Static idea you can share a variable across all instances. ie
class Person{
static String School = "Wandsworth Primary";
public Person(String name) {
this.name = name;
}
}
class Student extends Person{
public Student(String name, int grade){
super(name);
this.grade = grade;
}
public show() {
System.out.println(school);
}
}
Your child class, 'Student' has inherited the show method from the parent.
Hence, when you created an object of student, with some values b and BB, those values got displayed.
The values of the student , will be passed through student to parent since you called super(a,b) and will be displayed using the show() method which is obtained from it's parent class.
Hope this helps you.
This is not related to inheritance. You just don't understand the concept of classes.
The p and s that you created are completely independent things. They won't affect each other, so calling s.show() will never print the values in p.
"But s inherits from p though! So it must have a copy of p!" you argued. No, s does not inherit from p, only Student inherits from Person.
It is not that s has a copy of p, but instead, Student has a copy of Person.
In Student, there isn't a show method, but you can still call it. Why? Because Student inherits from Person, so the show method is "copied" to Student.
When you call show, what actually happens is that the show in Person is called:
System.out.println(this.name + "\n" + this.id);
As you can see, it prints the caller's (We know it's caller because of the this keyword) name and id. So who's the caller here? s! That's why it prints the student's name and id.
If you still don't understand, just think of Student like this:
class Student {
public String name;
String id;
void show() {
System.out.println(this.name + "\n" + this.id);
}
Student() {}
Student(String a, String b) {
System.out.println("Parent parameter");
this.name = name;
this.id = id;
}
}
See? I copied all the stuff from the Person class to Student!
Lets say i have a Super class Person and subclass Employee
I would like to create a person class first and then use it as a param to be placed into my employee class's constructor.
E.g. Public Empolyee(Person person....) (This produces a constructor not found error during compile time)
My Case scenario is that i have a Person object that has not been instantiated as an employee yet and later on i would like to use it to instantiate an Employee object and I would like to pass this person's variables over.
So how do i do this? Also please do explain if it should be done this way or not.
You directly get access to all Person class members via Employee class due to the inheritance relationship. You dont need to pass parent object to a child.
Pass all the necessary parameters to Employee and call super() from its constructor.
//Person constructor
Person(param1, param2){
}
class Employee extends Person
//Employee constructor
Employee(param1, param2){
super(param1, param2);
}
// New object
Employee emp = new Employee(param1, param2);
Also constructor dont return anything so remove the void in your question.
Child class automatically gets access of all the public, protected members of the parent and child also has reference to parent class.
why you want to pass parent class reference to Child class. Instead you can call parent class constructor from child class like this:
public Child(){
super()
}
According to the question below, we can do this:
public class Child1 extends Super1 {
private int l;
public Child1(Super1 s){
super(s);
}
public Child1(){
this.l=20;
}
}
public class Super1 {
private int k;
public Super1(){
}
public Super1(Super1 s){
k=s.k;
}
}
i dont see your inheritance logic here correctly.
you have answer already..see below
class person()
class employee extends person(here)
hence you get to access its variables and methods..
just curious why you need to instantiate employee and injecting person class which is already parent to employee.
Your Employee will work as a person.You can call every method or variable (except private variables and methods) of Person by Employee object. But still if you want to pass a Person object to the constructor of Employee class then you can do it as fallows-
public Employee(Person person,.......){
super();//or pass required parameters according to constructor of Person class
//do whatever you want
}
it will work perfectly.
try this:
//if your Person constructor looks like this
public Person(param1, param2){
}
//then your copy constructor would look like this
public Employee(Person p){
super(p.getParam1 p.getParam2);
}