Java Practice Solutions
1. Structural differences between an Abstract Class and an
Interface
Abstract Class vs Interface:
- Keyword:
Abstract Class → 'abstract' keyword
Interface → 'interface' keyword
- Methods:
Abstract Class → Can have abstract + concrete methods
Interface → Methods are abstract (until Java 8), can also have default/static methods
- Variables:
Abstract Class → Can have instance variables
Interface → Only public static final constants
- Inheritance:
Abstract Class → Single inheritance (extends one class)
Interface → Multiple inheritance (implements many interfaces)
- Constructors:
Abstract Class → Allowed
Interface → Not allowed
- Access Modifiers:
Abstract Class → Can have public, private, protected
Interface → All methods are public by default
2(a). Create multiple Employee objects in an array
class Employee {
String name;
int id;
Employee(String name, int id) {
[Link] = name;
[Link] = id;
}
void display() {
[Link]("ID: " + id + ", Name: " + name);
}
}
public class EmployeeTest {
public static void main(String[] args) {
Employee[] employees = new Employee[3];
for (int i = 0; i < [Link]; i++) {
employees[i] = new Employee("Employee" + (i + 1), i + 101);
}
for (Employee emp : employees) {
[Link]();
}
}
}
2(b). Login System with Username & Password
import [Link];
public class LoginSystem {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
String correctUser = "admin";
String correctPass = "1234";
while (true) {
[Link]("Enter username: ");
String user = [Link]();
[Link]("Enter password: ");
String pass = [Link]();
if ([Link](correctUser) && [Link](correctPass)) {
[Link]("Login Successful!");
break;
} else {
[Link]("Wrong credentials, try again.");
}
}
[Link]();
}
}