In: Computer Science
Programming Questions:
1) How do you build an array of objects of a superclass with its subclass objects?
2) How do you use an enhanced for-loop to traverse through an array while calling a static method(superclass x)?
3) How do you create a static method for a class that has the parent class reference variable?
**Include java coding examples for each question if possible
Note : I provided the answers for the three questions which u have asked for..I mentioned the question numbers in comment section. Thank You
/*********************************************/
/******* Employee.java ******/
public class Employee extends Person {
private double salary;
public Employee(String name, int age, double
salary) {
super(name, age);
this.salary = salary;
}
/**
* @return the salary
*/
public double getSalary() {
return salary;
}
/**
* @param salary
* the salary to set
*/
public void setSalary(double salary) {
this.salary = salary;
}
public static void display(Person p)
{
Person.display(p);
System.out.println("Age :
"+p.getAge());
}
}
/*********************************************/
/*********************************************/
/****** Person.java ******/
package org.students;
public class Employee extends Person {
private double salary;
public Employee(String name, int age,
double salary) {
super(name, age);
this.salary = salary;
}
/**
* @return the salary
*/
public double getSalary() {
return salary;
}
/**
* @param salary
* the salary to set
*/
public void setSalary(double salary) {
this.salary = salary;
}
/*
* 3. Static method which is having super class
reference variable
*/
public static void display(Person p)
{
Person.display(p);
System.out.println("Age :
"+p.getAge());
}
}
/*********************************************/
/*********************************************/
/******** Test.java ********/
public class Test {
public static void main(String[] args) {
/*
* 1. Creating an array of sub class
objects
* which is holding by super class
reference variable
*/
Person emps[] = { new
Employee("Mike", 23, 50000),
new Employee("Williams", 29, 66000),
new Employee("James", 28, 34000)
};
/*
* 2. Iterating over the array using
the enhanced for loop
*/
for(Person p : emps)
{
Employee.display(p);
System.out.println("__________________________");
}
}
}
/*********************************************/
/*********************************************/
Output:
/*********************************************/