This is my parent class
abstract public class Person {
private String name;
private Date birthday;
private double difficulty;
protected abstract String personType();
protected abstract Person clone();
Person(String name, Date birthday, double difficulty) {
this.name = name;
this.birthday = birthday;
this.difficulty = difficulty;
}
Person(Person copy) {
this.name = copy.name;
this.birthday = copy.birthday;
this.difficulty = copy.difficulty;
}
Person(){
this.name = "";
this.birthday = new Date();
this.difficulty = 0;
}
public String getName() {
return this.name;
}
public Date getBirthday() {
return this.birthday;
}
public double getDifficulty() {
return this.difficulty;
}
And I want to make a subclass called Singer with the same constructor variables. My question is, how do I initialize the variables "name", "birthday", and "difficulty" in the Singer subclass by calling onto the parent class Person?
public class Singer extends Person{
String debutAlbum;
Date debutAlbumReleaseDate;
Singer(String name, Date birthday, double difficulty, String debutAlbum, Date debutAlbumReleaseDate){
this.debutAlbum = debutAlbum;
this.debutAlbumReleaseDate = debutAlbumReleaseDate;
//im not sure what to put here for name, birthday, and difficulty
}
}
You can use 1 of these 3:
Using super() method (recommended):
Add in the first line on the constructor this line super(name, birthday, difficult).
This line will call the constructor of Person class for your object.
Notice: super method can be used only in the first line of the constructor
Add set() method:
In the Person class, add set method for each variable and then call them in the constructor.
Change access modifications:
Change the access modifications of each variable in Person class to protected or public and then use this.name = name;.
I have seen several get() and set() methods used for private fields. And I also understand why its being used.
But what I dont understand is that, I have my Student class with private fields in them. So why is it when I remove the get() and set(), it still works (for example, method to print).
Or is it still working because its in the same file class? but say if I try calling the private field without defining the get() and set() method from an external class. It wont work?
This is my code with the get() and set()
public class Student {
private String name;
private String address;
private String degreeName;
private String department;
private String yearCommence;
private long studentID;
private static int nextID = 901000 ;
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public String getDegreeName() {
return degreeName;
}
public String getDepartment() {
return department;
}
public String getYearCommence() {
return yearCommence;
}
public void setName(String name) {
this.name = name;
}
public void setAddress(String address) {
this.name = address;
}
public void setDegreeName(String degreeName) {
this.degreeName = degreeName;
}
public void setDepartment(String department) {
this.department = department;
}
public void setYearCommence(String yearCommence) {
this.department = yearCommence;
}
public Student(String name, String address, String degreeName, String department, String yearCommence, long StudentID) {
this.name = name;
this.address = address;
this.degreeName = degreeName;
this.department = department;
this.yearCommence = yearCommence;
this.studentID = nextID++;
}
public Student(String name, String address, String degreeName, String department, long studentID) {
this(name, address, degreeName, department, null, studentID);
}
public Student(String name, String address, String degreeName, long studentID) {
this(name, address, degreeName, null, null, studentID);
}
public Student(String name, String address, long studentID) {
this(name, address, null, null, null, studentID);
}
public Student(String name, long studentID) {
this(name, null, null, null, null, studentID);
}
public Student(long studentID) {
this(null, null, null, null, null, studentID);
}
#Override
public String toString() {
return "StudentInfo {" + "name=" + name + ", address=" + address + ", degreeName=" + degreeName + ", department=" + department + ", commence = " + yearCommence +", "+ " "+ "studentID = " + studentID+ "}";
}
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
Student student1 = new Student("Yusuf", "jl.ANU", "IT", "CECS", null, Student.nextID);
students.add(student1);
System.out.println(student1);
Student student2 = new Student("Ning", "jl.Cikini","IT", null, null, Student.nextID);
students.add(student2);
System.out.println(student2);
Student student3 = new Student("Boris", "jl.Babi", Student.nextID);
students.add(student3);
System.out.println(student3);
Student student4 = new Student(null, null, null, null, null, Student.nextID);
students.add(student4);
System.out.println(student4);
}
}
All of your functions are in the class that owns the private attributes and can therefore access all of them without needing a getter function. It should also be noted that because the main function is static it can only access other static members.
Private attributes are, by definition, only accessible by the same class. This means that methods in the class itself can access the private attributes. Methods in any other classes won't be able to access such private attributes and thus would need get/set methods.
There can be private fields in an class which have no get or set method. Your are able to use your class, but can't set or get the values of this fields from outside this class. If you have a constructer which have these private fields as parameters, these fields will be set on initialization, but can't be change afterwards on that instance.
It work mostly because you never used those getter/setter.
You create the instances and call toString on it (not directly, but System.out.println will do it)
But, let say you had another class where you build an instance Student student = new Student.... And you have :
student.name = name; //This is directly accessing the private field "name"
stuendt.setName(name); //This is using the setter of "name"
Java will not translate a direct access of the variable into a call of the getter/setter by itself, you have to do it. You can't expect the JVM to call setName if you write the first line.
For the scope where those values are accessible, I let you read the others answers. Don't need to say it one more time.
Please note that you are note using the parameter for the ID
public Student(String name, String address, String degreeName, String department, String yearCommence, long StudentID) {
this.name = name;
this.address = address;
this.degreeName = degreeName;
this.department = department;
this.yearCommence = yearCommence;
this.studentID = nextID++;
}
You still use nextID insteand of StudentID. Personnaly, I would not ask for that parameter if I am using a static value directly. You could simply remove it from the parameters list.
private fields are accessible from the same class. If you want the fields to be accessed from external class then you should declare the variable with public modifier.
You are over riding toString() method in your student class which is executed every time you print the object.
mutators and accessors are used to set the read/write behavour for the fields(from external).
I suggest you to look on access modifiers in java.
I am doing a project based around the concepts of inheritance and have created a super constructor which has two variables within itself (String, int), this super constructor is then called within a sub constructor that inherited the super constructors class. I then use two methods to return the properties of those variables within the constructors. The age property is outputting fine but the String property is returning null. Here's the code:
Animal super-class
abstract public class Animal
{
int age;
String name;
Animal(String name, int age)
{
this.age = age;
this.name = name;
}
Animal()
{
this("newborn", 0);
}
public String getName() {
return name;
}
public void setName(String newName) {
name = newName;
}
}
Wolf sub-class
public class Wolf extends Carnivore
{
String name;
int age;
Wolf(String name, int age)
{
this.name = name;
this.age = age;
}
Wolf()
{
super();
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
Main method class
public class Main {
public static void main(String[] args)
{
Wolf newWolf = new Wolf();
System.out.println("Name = " + newWolf.getName());
System.out.println("Age = " + newWolf.getAge());
}
}
Age is returning as 0 which is correct but System.out.println("Name = " + newWolf.getName()); seems to be returning null instead of "newborn". Any help on resolving this issue is appreciated thanks.
Update - I need the getName() method for another constructor that I haven't included in this example so is there a way to have them both exist?
The issue here is that you are defining your fields in the sub-class, you don't need to as they are inherited from the parent.
Your class has two sets of fields, one from the super (these are the ones set by your constructor, which is calling super() and the other from the child class (these are the ones returned by your getters, which are not initialized. the zero is int's default, not set either).
So simply remove the fields definition from the child class
I'm doing an assignment based around inheritance and I have created 2 constructors that are suppose to do different things. One constructor does not have any parameters and should produce a pre-defined value, the other constructor has 2 parameters which consist of a name and an age of types String and int. I have somehow reconfigured the two constructors so that they both do not produce what they should be. Here is the classes that these constructors are invoked in:
Animal (super class)
abstract public class Animal implements Comparable<Animal>
{
int age;
String name;
Animal(String name, int age)
{
this.age = age;
this.name = name;
}
Animal()
{
this("newborn", 0);
}
public int getAge()
{
return age;
}
public void setName(String newName)
{
name = newName;
}
String getName()
{
return name;
}
}
Carnivore
public class Carnivore extends Animal
{
Carnivore(String name, int age)
{
this.age = age;
this.name = name;
}
Carnivore()
{
super();
}
#Override
public int compareTo(Animal o)
{
//To change body of generated methods, choose Tools | Templates.
throw new UnsupportedOperationException("Not supported yet.");
}
}
Wolf
public class Wolf extends Carnivore
{
String name;
int age;
Wolf(String name, int age)
{
this.name = name;
this.age = age;
}
Wolf()
{
super();
}
String getName()
{
return name;
}
}
Main method
System.out.println("************1st constructor of Wolf************");
Wolf wolfExample = new Wolf("Bob", 2) {};
System.out.println("Name = " + wolfExample.getName());
System.out.println("Age = " + wolfExample.getAge());
System.out.println("************2nd constructor of Wolf************");
Wolf newWolf = new Wolf();
System.out.println("Name = " + newWolf.getName());
System.out.println("Age = " + newWolf.getAge());
Actual Output
************1st constructor of Wolf************
Name = Bob
Age = 0
************2nd constructor of Wolf************
Name = null
Age = 0
Expected Output
************1st constructor of Wolf************
Name = Bob
Age = 2
************2nd constructor of Wolf************
Name = newborn
Age = 0
The ages are returning their default value and the name for the second constructor is also returning null but I'm not too sure why. This is my first time working with multiple constructors so I'm a little confused as to ow it works so any help would be much appreciated, thanks.
Your base class seems correct, but you need to change your implementations.
Your Wolf and Carnivore constructors should be:
Wolf(String name, int age)
{
super(name, age);
}
Reason being, you are setting the local instance variables for each type, but calling getAge() method of the super class - this is getting the super's value of age, whose's value has not actually been assigned anywhere, and is given a default value of 0. This goes the same for name, which defaults to null.
You need to call super with the passed variables, and do not need to redefine them for each extended object.
This question already has answers here:
Java Reflection: How can I get the all getter methods of a java class and invoke them
(7 answers)
Closed 8 years ago.
I want to know if I can get the methods that returns class members.
For example I have a class called Person inside this class there is two members that are name and age and inside this class I have 4 methods as follow :
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
so if I use the method Person.class.getDeclaredMethods(); it returns all the methods that are declared inside this class and also Person.class.getDeclaredMethods()[0].getReturnType(); returns the return type of the method.
But what I need is to get the methods that returns the two variables name and age In this case the methods are public String getName() and public int getAge().
What can I do?
In your class name and age are not global. They would need to have a static before them to be global. In order to access your fields with an instance and reflection you could do something like
public static void main(String args[]) {
Person p = new Person("Elliott", 37);
Field[] fields = p.getClass().getDeclaredFields();
for (Field f : fields) {
try {
f.setAccessible(true);
String name = f.getName();
String val = f.get(p).toString();
System.out.printf("%s = %s%n", name, val);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output is (as I would expect)
name = Elliott
age = 37