0% found this document useful (0 votes)
17 views9 pages

CL 5

contrl lab exp 5

Uploaded by

Megha Saran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views9 pages

CL 5

contrl lab exp 5

Uploaded by

Megha Saran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

1.

Inheritance in Java: Basics

Inheritance allows a class (child or subclass) to inherit fields and methods from another class (parent or
superclass). This helps in code reusability and establishes a natural hierarchy between classes.

1. Write a Person class (called Person) with two fields: name and age. Then add a method displayInfo()
that prints the name and age.

2. Next, create a Student class that extends the Person class. Then add an additional field studentId.
Like this:

class Student extends Person {


int studentId;
}

3. Inside main(), create an object of the Student class. Set the fields and call the displayInfo() method.

public class Main {


public static void main(String[] args) {
Student student = new Student();
student.name = "XYZ";
student.age = 20;
student.studentId = ENGGCS101;

student.displayInfo();
System.out.println("Student ID: " + student.studentId);
}
}
4. Run this program and observe the output. Notice how the Student class inherits the
displayInfo() method from the Person class.

5. Modify the Person class by adding methods that set and return (get) the value of each field. Call
them getName(), setName(), getAge(), setAge(). Similarly, getStudentID() and setStudentID() in
the Student class. See how they can be accessed in the main program.
2. Method Overriding

When a subclass provides a specific implementation of a method that is already present in its superclass,
we call it method overriding.

1. In the Student class, override the displayInfo() method to include the studentId.

class Student extends Person {


int studentId;
void displayInfo() {
super.displayInfo(); // Call the parent class method
System.out.println("Student ID: " + studentId);
}
}

2. In the main method, use the Student object again and call displayInfo().

public class Main {


public static void main(String[] args) {
Student student = new Student();
student.name = "ABC";
student.age = 20;
student.studentId = ENGGCS102;

student.displayInfo(); // Calls overridden method


}
}

3. Run the program and notice how the displayInfo() method in the Student class is called instead
of the one in the Person class.

4. Assuming you’ve added all the getter/setter methods in the previous question, override the
setAge(int age) method to set as (age + 10). (Make sure you use the same name as in parent).
Test and observe the behavior of the method.
3. Access Modifiers in Inheritance

Our focus here will be to understand how different access modifiers affect inheritance. We have three
access modifiers (public, protected, private) and one default. Briefly, this is what each means:
• private: Not accessible in child classes
• protected: Accessible within the package and in subclasses
• public: Accessible everywhere
• No modifier (default): Accessible within the package

1. In the Person class, change the access modifiers of fields and methods as shown.

class Person {
private String name; // Private
protected int age; // Protected

private void displayPrivateInfo() {


System.out.println("This is private info");
}

protected void displayInfo() {


System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}

2. Try to access name and displayPrivateInfo() in the Student class. Notice what happens when you
change the access modifiers.

class Student extends Person {


int studentId;

void displayInfo() {

System.out.println("Name: " + name); // Error?


displayPrivateInfo(); // Error?
}
}

3. Experiment with visibility by trying to access from main(). Work with different modifiers for both
data fields and methods and observe errors or successful accesses.
4. The super Keyword

The super keyword refers to the parent class. Can be used to invoke parent class's constructor/ methods

1. Add a constructor in the Person class and invoke it in the Student class using super.

class Person {
String name;
int age;

Person(String name, int age) {


this.name = name;
this.age = age;
}

void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}

class Student extends Person {


int studentId;

Student(String name, int age, int studentId) {


super(name, age); // Call parent constructor
this.studentId = studentId;
}

void displayInfo() {
super.displayInfo();
System.out.println("Student ID: " + studentId);
}
}

2. Update the main method to use the constructor with arguments.

public class Main {


public static void main(String[] args) {
Student student = new Student("XYZ", 20, ENGGCS101);
student.displayInfo();
}
}

3. Which constructor is called first? Observe.

4. Modify the Person class to have two more constructors and use super() to invoke different
constructors from the Student class.
5. Polymorphism and Inheritance

Polymorphism allows objects of different classes to be treated as objects of a common superclass. This is
most often used with method overriding, where the correct method is called based on the object's
runtime type.

1. Create another subclass Teacher and override the displayInfo() method.

class Teacher extends Person {


String subject;

Teacher(String name, int age, String subject) {


super(name, age);
this.subject = subject;
}

void displayInfo() {
super.displayInfo();
System.out.println("Subject: " + subject);
}
}

2. In the main method, create an array of Person objects that includes both Student and Teacher.

public class Main {


public static void main(String[] args) {
Person[] people = new Person[2];

people[0] = new Student("XYZ", 20, ENGGCS101);


people[1] = new Teacher("PROF", 40, "AdvProgLab");

for (Person person : people) {


person.displayInfo();
System.out.println();
}
}
}

3. Notice how the correct displayInfo() method is called for each object, even though they are all
stored as Person types.
6. Abstract Classes and Interfaces

An abstract class is a class that contains one or more abstract methods that must be implemented by
subclasses. An abstract class cannot be instantiated (we cannot make objects of that class). On the other
hand, an Interface is a reference type in Java that can contain only constants, method signatures,
default methods, static methods, and nested types.

1. Modify the Person class to be abstract and include an abstract method work() without any
implementation. This converts it into an abstract class.

abstract class Person {


String name;
int age;

Person(String name, int age) {


this.name = name;
this.age = age;
}

void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}

abstract void work(); // Abstract method


}
2. In Student and Teacher, implement the work() method.

class Student extends Person {


int studentId;

Student(String name, int age, int studentId) {


super(name, age);
this.studentId = studentId;
}

void displayInfo() {
super.displayInfo();
System.out.println("Student ID: " + studentId);
}

void work() {
System.out.println(name + " is studying.");
}
}
class Teacher extends Person {
String subject;

Teacher(String name, int age, String subject) {


super(name, age);
this.subject = subject;
}

void displayInfo() {
super.displayInfo();
System.out.println("Subject: " + subject);
}

void work() {
System.out.println(name + " is teaching.");
}
}

3. Next, create an interface called Payable which will represent entities that can receive payment.
(Since teachers have salaries but students don’t). This interface will have a single method called
getPayment().

interface Payable {
double getPayment();
}

4. Implement the interface in the Teacher class. One way to do this would be to update our
Teacher class like this:

class Teacher extends Person implements Payable {


String subject;
double salary;

Teacher(String name, int age, String subject, double salary) {


super(name, age);
this.subject = subject;
this.salary = salary;
}

public double getPayment() {
return salary;
}
}
5. Create Teacher and Student objects, call their methods.

public class Main {


public static void main(String[] args) {
Person[] people = new Person[2];

people[0] = new Student("ABC", 20, “ENGGCS102”);


people[1] = new Teacher("PROF", 40, "AdvProgLab");

for (Person person : people) {


person.displayInfo();
person.work();
if (person instanceof Payable) {
Payable p = (Payable) person;
System.out.println("Payment: Rs." + p.getPayment());
}
System.out.println();
}
}
}

4. Run the program. Observe how the Teacher class can now provide salary information using the
getPayment() method. Note the use of the instanceof operator. What does it do? Also observe
how work() is invoked correctly in the code. This demonstrates the functionality provided by the
Payable interface. Explore further: What is the need for using interfaces in Java?
7. Final Classes and Methods

The final keyword: A final class cannot be extended. A final method cannot be overridden by subclasses.

1. Make a new Admin class and mark it as final.

final class Admin {


String role = "Administrator";

final void manage() {


System.out.println("Managing system.");
}
}

2. Try to extend the Admin class. What happens?

3. Make Admin non-final (remove final from the class definition). Then try to override the
manage() method in a sub-class. What do you observe?

You might also like