Slip No 24 Q B

Q.Create a package TYBBACA with two classes as class Student (Rno, SName, Per)with a method disp() to display details of N Students and class Teacher (TID, TName,Subject) with a method disp() to display the details of teacher who is teaching Java
subject. (Make use of finalize() method and array of Object) [25 M]

package TYBBACA;

import java.util.Scanner;

public class Student
{
    int rno;
    String sname;
    double per;

    public void accept()
    {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter Roll No: ");
        rno = sc.nextInt();

        System.out.print("Enter Name: ");
        sname = sc.next();

        System.out.print("Enter Percentage: ");
        per = sc.nextDouble();
    }

    public void disp()
    {
        System.out.println(rno + "\t" + sname + "\t" + per);
    }

    protected void finalize()
    {
        System.out.println("Student object destroyed");
    }
}

Teacher Class

package TYBBACA;

import java.util.Scanner;

public class Teacher
{
    int tid;
    String tname;
    String subject;

    public void accept()
    {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter Teacher ID: ");
        tid = sc.nextInt();

        System.out.print("Enter Teacher Name: ");
        tname = sc.next();

        System.out.print("Enter Subject: ");
        subject = sc.next();
    }

    public void disp()
    {
        if(subject.equalsIgnoreCase("Java"))
        {
            System.out.println("Teacher teaching Java:");
            System.out.println(tid + "\t" + tname + "\t" + subject);
        }
    }

    protected void finalize()
    {
        System.out.println("Teacher object destroyed");
    }
}
Main Class
import TYBBACA.*;
import java.util.Scanner;

class PackageDemo
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);

        // Student array of objects
        System.out.print("Enter number of students: ");
        int n = sc.nextInt();

        Student s[] = new Student[n];

        for(int i = 0; i < n; i++)
        {
            s[i] = new Student();
            s[i].accept();
        }

        System.out.println("\nStudent Details:");
        System.out.println("RNo\tName\tPer");
        for(int i = 0; i < n; i++)
        {
            s[i].disp();
        }

        // Teacher array
        System.out.print("\nEnter number of teachers: ");
        int m = sc.nextInt();

        Teacher t[] = new Teacher[m];

        for(int i = 0; i < m; i++)
        {
            t[i] = new Teacher();
            t[i].accept();
        }

        System.out.println();
        for(int i = 0; i < m; i++)
        {
            t[i].disp();
        }

        System.gc();   // invoke finalize
    }
}
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top