Nothing Special   »   [go: up one dir, main page]

Java Week - 8 Pratical

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

Week – 8

class Teacher {
//fields of parent class
String designation = "Teacher";
String collegeName = "Beginnersbook";

//method of parent class


void does(){
System.out.println("Teaching");
}
}

public class PhysicsTeacher extends Teacher{


//field of child class
String mainSubject = "Physics";
public static void main(String args[]){
PhysicsTeacher obj = new PhysicsTeacher();
//accessing the fields of parent class
System.out.println(obj.collegeName);
System.out.println(obj.designation);

System.out.println(obj.mainSubject);

//accessing the method of parent class


obj.does();
}
}
In the above program we have a base class Teacher and a sub class PhysicsTeacher. Child
class inherits the following fields and methods from parent class:

 Properties: designation and collegeName properties
 Method: does()

Child classes like MathTeacher, MusicTeacher and PhysicsTeacher do not need to write this


code and can access these properties and method directly from base class.

1) Single Inheritance
Class A
{
public void methodA()
{
System.out.println("Base class method");
}
}

Class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}

Multilevel Inheritance
class Car{
public Car()
{
System.out.println("Class Car");
}
public void vehicleType()
{
System.out.println("Vehicle Type: Car");
}
}
class Maruti extends Car{
public Maruti()
{
System.out.println("Class Maruti");
}
public void brand()
{
System.out.println("Brand: Maruti");
}
public void speed()
{
System.out.println("Max: 90Kmph");
}
}
public class Maruti800 extends Maruti{

public Maruti800()
{
System.out.println("Maruti Model: 800");
}
public void speed()
{
System.out.println("Max: 80Kmph");
}
public static void main(String args[])
{
Maruti800 obj=new Maruti800();
obj.vehicleType();
obj.brand();
obj.speed();
}
}
Design a class & implement java program and check
compliance with OCP .
/*File name = run.java*/
Interface shape {
Public double calculateArea();
}
Class rectangle implements shape {
Double length;
Double width;
Public double calculateArea() {
Return length * width;
}
}
Class circle implement shape {
Public double radius;
Public double calculateArea() {
Return (22.0/7)* radius * radius;
}
}

You might also like