I am trying to print the 3 variables 2 from the superclass and one from the subclass but the variable of the subclass always printed out null when I use the mentioned method
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner info=new Scanner(System.in);
System.out.println("Enter the father name ");
String firstname=info.next();
System.out.println("Enter the grandfather name ");
String lastname=info.next();
System.out.println("Enter the child name ");
String name=info.next();
child one = new child(firstname,lastname,name);
one.print_names();
}
}
the classes
class dad{
String firstname;
String lastname;
dad (String firstname,String lastname){
this.firstname=firstname;
this.lastname=lastname;
}
}
class child extends dad{
String name;
child(String firstname,String lastname,String name){
super(firstname,lastname);
name=name;
}
String childprint(){
System.out.println(name);
return name;
}
String print_names(){
System.out.println( "your name is= " name " " firstname " " lastname);
return name;
}
}
The output
Enter the father name
k
Enter the grandfather name
g
Enter the child name
f
your name is= null k g
CodePudding user response:
In your child constructor you wrote
name = name
.
You need to write this.name
instead of just name
.
When you write name
, it refers to the parameter. When you write this.name
, it refers to the object member named name
.
CodePudding user response:
There are two things I'd like to address here:
- In java we capitalize class names like so: Data or Child
- When using a constructor, use this. to assign the value to the class instance rather than the constructor arg
CodePudding user response:
I think you only need to initialize your "name" parameter in the child constructor. I mean: where you declare "name=name" you should state "this.name = name" . That will tell the constructor that the value of the value of the variable name is the one provided inside the parenthesis. I hope it helps!