class Human{
// declared instance variables
String name;
int age;
// instance method
void speak(){
System.out.println("My name is: " + name);
}
int calculateYearsToRetirement(){
int yearsLeft = 65 - age;
return yearsLeft;
}
int getAge(){
return age;
}
String getName(){
return name;
}
// so when I create an instance, i can't have constructor?
// error here
Human(int age){
age = this.age;
}
}
}
public class GettersAndReturnValue {
public static void main(String[] args) {
// error here because I created a constructor Human(int a)
Human human1 = new Human();
human1.name = "Joe";
human1.age = 25;
human1.speak();
int years = human1.calculateYearsToRetirement();
System.out.println("Years till retirements " + years);
int age = human1.getAge();
System.out.println(age);
}
}
I tried to create a constructor Human(int age) to practice 'this' keyword and to change the age from 25 to something else but I get an error because I have one Human class and one Human constructor. When I try to create an instance of Human Type in my main method, eclipse is asking me to remove the constructor
You've swapped the order in your assignment,
Human(int age){
age = this.age;
}
should be something like (don't forget to initialize name too)
Human(int age){
this.age = age;
this.name = "Unknown";
}
You're assigning the default value 0 to the passed in parameter. If you provide a constructor then the compiler will no longer insert the default constructor,
Human() {
this.age = 0;
this.name = "Unknown";
}
and you might as well add a constructor that takes the name,
Human(int age, String name) {
this.age = age;
this.name = name;
}
then you could call it (in main) like
Human human1 = new Human(25, "Joe");
// human1.name = "Joe";
// human1.age = 25;
You have to create a no parameter constructor, because when you are calling Human h = new Human();, you are calling a no parameter constructor.
Try doing this instead:
Human h = new Human(age);
When you create a non-empty constructor, the empty constructor will not be available anymore. You do can have more than one constructor, but if you want the no-argument constructor along with other, you will have to recreate it.
//Please, make it public for constructors
public Human(int age){
this.age = age; //this.age first, to receive the parameter age
}
public Human() {} //Empty constructor. It doesn't has to be a content.
So you call:
Human humanOne = new Human(); //Using no-argument constructor
Human humanTwo = new Human(25); //Using constructor with int to set age
When you create a constructor in the class, it will no longer use the default constructor. In your code, you've created a public Human(int) constructor, so there is no default constructor. Because of that, you cannot create human object like this:
Human a = new Human();
To do that, you have to manually implement a no-argument Human constructor.
Here is a solution:
class Human{
String name;
int age;
//default constructor
public Human (){
}
//paramete constructor
public Human(int a){
this.age=a;
}
void speak(){
System.out.println("My name is: " + this.name);
}
int calculateYearsToRetirement(){
int yearsLeft = 65 - age;
return yearsLeft;
}
int getAge(){
return this.age;
}
String getName(){
return this.name;
}
}
Here's the working code :
Create a class GettersAndReturnValue and add this. You need a empty constructor.
class Human{
// declared instance variables
String name;
int age;
// instance method
void speak(){
System.out.println("My name is: " + name);
}
int calculateYearsToRetirement(){
int yearsLeft = 65 - age;
return yearsLeft;
}
int getAge(){
return age;
}
String getName(){
return name;
}
// so when I create an instance, i can't have constructor?
// error here
Human(int age){
this.age = age;
}
public Human() {
// TODO Auto-generated constructor stub
}
}
public class GettersAndReturnValue {
public static void main(String[] args) {
// error here because I created a constructor Human(int a)
Human human1 = new Human();
human1.name = "Joe";
human1.age = 25;
human1.speak();
int years = human1.calculateYearsToRetirement();
System.out.println("Years till retirements " + years);
int age = human1.getAge();
System.out.println(age);
}
}
Output :
My name is: Joe
Years till retirements 40
25
Related
I have a program I am working with to help me practice my coding skills. The program has the following scenario: there is a classroom of 20 students, where the record is taken of the students' names, surnames, and age. Half of these students take part in the school's athletics. Here, record is kept of their races that they have done and the ones they've won.
In this program, I have three classes:
runStudents - class with main method
Students (String name, String surname, int age) - parental class
AthleticStudents (String name, String surname, int age, int races, int victories) - sub class
The user should be able to add another race (and win) to the object. As seen by the code provided, an Array is created to store the 20 Students objects. I have to be able to access a method to alter the object in the array, but this method is not in the parental class (the class the objects are created from.
public class Students
{
private String name;
private String surname;
private int age;
public Students()
{
}
public Students(String name, String surname, int age)
{
this.name = name;
this.surname = surname;
this.age = age;
}
public String getName()
{
return this.name;
}
public String getSurname()
{
return this.surname;
}
public double getAge()
{
return this.age;
}
public void setName(String name)
{
this.name = name;
}
public void setSurname(String surname)
{
this.surname = surname;
}
public void setAge(int age)
{
this.age = age;
}
public String toString()
{
return String.format("name\t\t: %s\nsurname\t\t: %s\nage\t\t: %s",
this.name, this.surname, this.age);
}
}
public class AthleticStudents extends Students
{
private int races;
private int victories;
public AthleticStudents()
{
}
public AthleticStudents(String name, String surname, int age, int
races, int victories)
{
super(name, surname, age);
this.races = races;
this.victories = victories;
}
public int getRaces()
{
return this.races;
}
public int getVictories()
{
return this.victories;
}
public void setRaces(int races)
{
this.races = races;
}
public void setVictories(int victories)
{
this.victories = victories;
}
public void anotherRace()
{
this.races = this.races + 1;
}
public void anotherWin()
{
this.victories = this.victories + 1;
}
public String toString()
{
return super.toString() + String.format("\nnumber of races\t:
%s\nnumber of wins\t: %s", this.races, this.victories);
}
}
public class runStudents
{
public static void main(String[]args)
{
Students[] myStudents = new Students[20];
myStudents[0] = new Students("John", "Richards", 15);
myStudents[1] = new AthleticStudents("Eva", "Grey", 14, 3, 1);
myStudents[2] = new Students("Lena", "Brie", 15);
for (int i = 0; i < 3; i++)
System.out.println(myStudents[i].toString() + "\n\n");
}
}
I want to be able to do the following:
AthleticStudents[1].anotherRace();
but cannot do so as the array object is derived from the parental class, and I declared the method in the sub class. How can I link the two?
I assume that you create an array of the parent class instances. Just cast the instance this way (you better check whether the element is the instance of a subclass):
if (AthleticStudents[1] instanceof AthleticStudents)
((AthleticStudents) AthleticStudents[1]).anotherRace();
I'm not sure if this is exactly what you're looking for but it worked well for me. Instead of trying to access AthleticStudents method anotherRace() like that, try this in your main method.
Students[] myStudents = new Students[20];
myStudents[0] = new Students("John", "Richards", 15);
myStudents[1] = new AthleticStudents("Eva", "Grey", 14, 3, 1);
myStudents[2] = new Students("Lena", "Brie", 15);
AthleticStudents addRace= (AthleticStudents)myStudents[1];
addRace.anotherRace(); //This will increment Eva's race count to 4
for (int i = 0; i < 3; i++)
System.out.println(myStudents[i].toString() + "\n\n");
All I did was cast the element into an object AthleticStudents named 'addRace'. By casting myStudents[1] to this new object you are able to access all of AthleticStudents methods.
I just saw the other answer posted which works just as well!
Hope this helps!
I’m not sure that i understand your question, because you are a bit inconsistent with your capitalization. runStudents is a class, while AthleticStudents is both a class and an array. But i’ll try.
IF i did understand your question, you have an array Student[] studentArray. Some Student objects in studentArray are AthleticStudents, others are not. You have a specific AthleticStudent eva which is in studentArray[] having let’s say index 1, and you want to add to her anotherRace(). Your call studentArray[1].anotherRace does not compile because the compiler treats that element as a Student and not as a AthleticStudent.
The trick is to cast the element to AthleticStudent. I omit the test of the element of being really an AthleticStudent; you will have to do that test in your code.
((AthleticStudent) studentArray[1]).anotherRace();
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.
class AStudent {
private String name;
public int age;
public void setName(String inName) {
name = inName;
}
public String getName() {
return name;
}
}
public class TestStudent2 {
public static void main(String s[]) {
AStudent stud1 = new AStudent();
AStudent stud2 = new AStudent();
stud1.setName("Chan Tai Man");
stud1.age = 19;
stud2.setName("Ng Hing");
stud2.age = -23;
System.out.println("Student: name="+stud1.getName()+
", age=" + stud1.age);
System.out.println("Student: name="+stud2.getName()+
", age=" + stud2.age);
}
}
How can I enhance the class AStudent by adding data encapsulation to the age attribute. If the inputted age is invalid, I want to print an error message and set the age to 18.
First, modify age so that it isn't public. Then add accessor and mutator methods (in the mutator, check for an invalid value - and set it to 18). Something like,
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
if (age < 0) {
System.err.println("Invalid age. Defaulting to 18");
age = 18;
}
this.age = age;
}
Then you could use it with something like setName
stud1.setAge(19);
and
stud2.setAge(-23);
And you could make it easier to display by overriding toString in AStudent like
#Override
public String toString() {
return String.format("Student: name=%s, age=%d", name, age);
}
Then you can print yor AStudent instances like
System.out.println(stud1); // <-- implicitly calls stud1.toString()
System.out.println(stud2);
You are using encapsulation for the name attribute. You could do the same for age.
class AStudent {
// ...
private int age;
public void setAge(int age) {
this.age = age;
if (age < 1) {
this.age = age;
}
}
}
The above code changes the age attribute to private so that access is restricted to the getter and setter. So you will also have to add a getter method and change TestStudent2 to use the new getter and setter.
What makes an age invalid? The above code assumes any value less than 1 is invalid.
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