Unit 5, 9 & 10
Unit 5 Hack (Putting it all together):
Demonstrate the usage of classes and core concepts of unit 5
Create a class and tester method which incorporates all core ideas taught in this post
Class which has a constructor which sets at least 1 public and 1 private attribute (incorporate “this” keyword)
Class which has public and private attributes and methods
Class which has at least 1 static attribute
Class which has getters and setters for at least 1 private attribute
Make sure to create a tester method that verifies that your class is working and shows the getters and setters working
public class Student {
private String name;
private int id;
private static int SID = 0; //static
public Student(String name){
this.name = name;
this.id = ++SID;
}
public String getName(){
return name;
}
public int getID(){
return id;
}
public void setName(String newName){
this.name = newName;
}
public String toString(){
return getName() + getID();
}
public static int getCount(){
return SID;
}
public static void main(String[] args){
}
}
Student.main(null);
Hack 2 (Putting it all together):
Demonstrate the usage of inheritance, polymorphism and overriding methods
Create a parent class of your choice
Create 2 subclasses from that parent superclass
incorporate some data and atleast one method into each class, using super keyword
Override superclass method in the subclasses
Use a tester method to create objects from the superclass that take on the forms of the subclasses, and print some outputs
public class Person {
private String name;
public Person(String name){
this.name = name;
}
public String getName(){
return name;
}
public void job() {
System.out.println("Work");
}
}
class Student extends Person {
public Student(String name){
super(name);
}
@Override
public void job() {
System.out.println("Learn");
}
public static void main(String[] args) {
Student student1 = new Student("Emily");
System.out.println(student1.getName());
student1.job();
}
}
Student.main(null);
class Teacher extends Person {
public Teacher(String name){
super(name);
}
@Override
public void job() {
System.out.println("Teach");
}
public static void main(String[] args) {
Teacher teacher1 = new Teacher("Alice");
System.out.println(teacher1.getName());
teacher1.job();
}
}
Teacher.main(null);
public class Factorial {
public static int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
public static void main(String[] args) {
System.out.println(factorial(3)); //1*2*3
}
}
Factorial.main(null);