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

HARSHVARDHAN POYREKAR

ASSIGNMENT 2 : Inheritance
23101B0069
(1) Simple Inheritance

class Animal {

void sound() {

System.out.println("Animal makes a sound");

class Dog extends Animal {

void bark() {

System.out.println("Dog barks");

public class Main {

public static void main(String[] args) {

Dog myDog = new Dog();

myDog.sound();

myDog.bark();

OUTPUT:
(2) Constructor Inheritance

class Vehicle {

Vehicle() {

System.out.println("Vehicle constructor");

void start() {

System.out.println("Vehicle starting...");

class Car extends Vehicle {

Car() {

System.out.println("Car constructor");

void drive() {

System.out.println("Car driving...");

public class Main {

public static void main(String[] args) {

Car myCar = new Car();

myCar.start();

myCar.drive();

OUTPUT:
(3) Method Overriding

class Shape {

void draw() {

System.out.println("Drawing a shape");

class Circle extends Shape {

void draw() {

System.out.println("Drawing a circle");

public class Main {

public static void main(String[] args) {

Circle myCircle = new Circle();

myCircle.draw();

OUTPUT:
(4) Inherited Variable

class Person {

String name;

Person(String name) {

this.name = name;

class Student extends Person {

int studentId;

Student(String name, int studentId) {

super(name);

this.studentId = studentId;

public class Main {

public static void main(String[] args) {

Student student = new Student("Harsh", 123);

System.out.println("Name: " + student.name);

System.out.println("Student ID: " + student.studentId);

OUTPUT:
(5) Triangle Class

class Shape {

void draw() {

System.out.println("Drawing a shape");

class Rectangle extends Shape {

void drawRectangle() {

System.out.println("Drawing a rectangle");

class Circle extends Shape {

void drawCircle() {

System.out.println("Drawing a circle");

public class Main {

public static void main(String[] args) {

Rectangle myRectangle = new Rectangle();

myRectangle.draw();

myRectangle.drawRectangle();

Circle myCircle = new Circle();

myCircle.draw();

myCircle.drawCircle();

OUTPUT:

You might also like