Create a class with a method that prints "This is parent class" and its subclass with another method that prints "This is child class". Now, create an object for each of the class and call
1 - method of parent class by object of parent class
2 - method of child class by object of child class
3 - method of parent class by object of child class
classPclass{publicvoidpmethod(){System.out.println("This is parent class");}}classCclassextendsPclass{publicvoidcmethod(){System.out.println("This is child class");}}classAns{publicstaticvoidmain(String[]args){Pclassm=newPclass();Cclassn=newCclass();m.pmethod();n.cmethod();n.pmethod();}}
2.
In the above example, declare the method of the parent class as private and then repeat the first two operations (You will get error in the third).
3.
Create a class named 'Member' having the following members:
Data members
1 - Name
2 - Age
3 - Phone number
4 - Address
5 - Salary
It also has a method named 'printSalary' which prints the salary of the members.
Two classes 'Employee' and 'Manager' inherits the 'Member' class. The 'Employee' and 'Manager' classes have data members 'specialization' and 'department' respectively. Now, assign name, age, phone number, address and salary to an employee and a manager by making an object of both of these classes and print the same.
classMember{Stringname;intage;Stringnumber;Stringaddress;intsalary;publicvoidprintSalary(){System.out.println(salary);}}classEmployeeextendsMember{Stringspecialization;}classManagerextendsMember{Stringdepartment;}classAns{publicstaticvoidmain(String[]args){Employeee=newEmployee();e.name="xyz";e.age=23;e.number="986****";e.address="xyzxyz";e.salary=1231;e.specialization="xyzxyz";Managerm=newManager();//Same goes for Manager}}
4.
Create a class named 'Rectangle' with two data members 'length' and 'breadth' and two methods to print the area and perimeter of the rectangle respectively. Its constructor having parameters for length and breadth is used to initialize length and breadth of the rectangle. Let class 'Square' inherit the 'Rectangle' class with its constructor having a parameter for its side (suppose s) calling the constructor of its parent class as 'super(s,s)'. Print the area and perimeter of a rectangle and a square.
5.
Now repeat the above example to print the area of 10 squares.
Hint-Use array of objects
Create a class named 'Shape' with a method to print "This is This is shape". Then create two other classes named 'Rectangle', 'Circle' inheriting the Shape class, both having a method to print "This is rectangular shape" and "This is circular shape" respectively. Create a subclass 'Square' of 'Rectangle' having a method to print "Square is a rectangle". Now call the method of 'Shape' and 'Rectangle' class by the object of 'Square' class.