0% found this document useful (0 votes)
21 views

Inheritance

The document contains examples of inheritance in Java including defining subclasses that extend superclass behaviors. It also demonstrates polymorphism through examples where a reference variable of a parent class can refer to an object of a subclass, allowing the overriding subclass method to be called. Finally, it shows an example of implementing inheritance where the Cylinder subclass extends the Circle superclass and inherits its properties while adding its own height property.

Uploaded by

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

Inheritance

The document contains examples of inheritance in Java including defining subclasses that extend superclass behaviors. It also demonstrates polymorphism through examples where a reference variable of a parent class can refer to an object of a subclass, allowing the overriding subclass method to be called. Finally, it shows an example of implementing inheritance where the Cylinder subclass extends the Circle superclass and inherits its properties while adding its own height property.

Uploaded by

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

class Animal{

void eat(){System.out.println("A...");}
}
class Dog extends Animal{
void bark(){System.out.println("B...");}
}

class Main{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
B...
A...

class Animal{
void eat(){System.out.println("A...");}
}

class Dog extends Animal{


void bark(){System.out.println("B...");}
}

class BabyDog extends Dog{


void weep(){System.out.println("C...");}
}

class Main{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}

C
B
A

class Animal{
void eat(){System.out.println("eating...");}
}

class Dog extends Animal{


void bark(){System.out.println("barking...");}
}

class Cat extends Animal{


void meow(){System.out.println("meowing...");}
}

class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark(); //would throw Conpile Time Error
}}

o/p
meowing...
eating...

class Animal{
void eat(){System.out.println("A...");}
}

class Dog extends Animal{


void bark(){System.out.println("B...");}
}

class Cat extends Animal{


void meow(){System.out.println("C...");}
}

class Main{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark(); //would throw Conpile Time Error
}}

o/p
C
A

// This porgram gives COMPILE TIME ERROR

class A{
void msg(){System.out.println("Hello");}
}

class B{
void msg(){System.out.println("Welcome");}
}

class C extends A,B{ //suppose if it were possible

Public Static void main(String args[]){


C obj=new C();
obj.msg(); //Now which msg() method would be invoked?
}
}

class Calculation {
int z;

public void addition(int x, int y) {


z = x + y;
System.out.println("The sum of the given numbers:"+z);
}

public void subtraction(int x, int y) {


z = x - y;
System.out.println("The difference between the given numbers:"+z);
}
}

public class My_Calculation extends Calculation {


public void multiplication(int x, int y) {
z = x * y;
System.out.println("The product of the given numbers:"+z);
}
}
class Main
‘{
public static void main(String args[]) {
int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
}
}

class Superclass {
int age;

Superclass(int age) {
this.age = age;
}

public void getAge() {


System.out.println("The value of the variable named age in super class is: " +age);
}
}

public class Subclass extends Superclass {


Subclass(int age) {
super(age);
}

public static void main(String argd[]) {


Subclass s = new Subclass(24);
s.getAge();
}
}

class Super_class {
int num = 20;

// display method of superclass


public void display() {
System.out.println("This is the display method of superclass");
}
}

public class Sub_class extends Super_class {


int num = 10;

// display method of sub class


public void display() {
System.out.println("This is the display method of subclass");
}

public void my_method() {


// Instantiating subclass
Sub_class sub = new Sub_class();

// Invoking the display() method of sub class


sub.display();

// Invoking the display() method of superclass


super.display();

// printing the value of variable num of subclass


System.out.println("value of the variable named num in sub class:"+ sub.num);

// printing the value of variable num of superclass


System.out.println("value of the variable named num in super class:"+ super.num);
}

public static void main(String args[]) {


Sub_class obj = new Sub_class();
obj.my_method();
}
}

class Animal {
public void move() {
System.out.println("Animals can move");
}
}

class Dog extends Animal {


public void move() {
System.out.println("Dogs can walk and run");
}
}

public class TestDog {

public static void main(String args[]) {


Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object

a.move(); // runs the method in Animal class


b.move(); // runs the method in Dog class
}
}

class Animal {
public void move() {
System.out.println("Animals can move");
}
}

class Dog extends Animal {


public void move() {
System.out.println("Dogs can walk and run");
}
public void bark() {
System.out.println("Dogs can bark");
}
}

public class TestDog {


public static void main(String args[]) {
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object

a.move(); // runs the method in Animal class


b.move(); // runs the method in Dog class
b.bark(); // ERROR - b's reference type Animal doesn't have a bark method
}
}

class Animal {
public void move() {
System.out.println("Animals can move");
}
}

class Dog extends Animal {


public void move() {
super.move(); // invokes the super class method
System.out.println("Dogs can walk and run");
}
}

public class TestDog {

public static void main(String args[]) {


Animal b = new Dog(); // Animal reference but Dog object
b.move(); // runs the method in Dog class
}
}

class Bike{
void run(){System.out.println("running");}
}
class Main extends Bike{
void run(){System.out.println("running safely with 60km");}

public static void main(String args[]){


Bike b = new Main();//upcasting
b.run();
}
}

class Bank{
float getRateOfInterest(){return 0;}
}
class SBI extends Bank{
float getRateOfInterest(){return 8.4f;}
}
class ICICI extends Bank{
float getRateOfInterest(){return 7.3f;}
}
class AXIS extends Bank{
float getRateOfInterest(){return 9.7f;}
}
class TestPolymorphism{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
b=new ICICI();
System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());
b=new AXIS();
System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());
}
}

class Shape{
void draw(){System.out.println("drawing...");}
}
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle...");}
}
class Circle extends Shape{
void draw(){System.out.println("drawing circle...");}
}
class Triangle extends Shape{
void draw(){System.out.println("drawing triangle...");}
}
class TestPolymorphism2{
public static void main(String args[]){
Shape s;
s=new Rectangle();
s.draw();
s=new Circle();
s.draw();
s=new Triangle();
s.draw();
}
}
class Circle {
private double radius;
private String color;

public Circle() {
this.radius = 1.0;
this.color = "red";
System.out.println("Construced a Circle with Circle()"); // for debugging
}
public Circle(double radius) {
this.radius = radius;
this.color = "red";
System.out.println("Construced a Circle with Circle(radius)"); // for debugging
}
public Circle(double radius, String color) {
this.radius = radius;
this.color = color;
System.out.println("Construced a Circle with Circle(radius, color)"); // for debugging
}
public double getRadius() {
return this.radius;
}
public String getColor() {
return this.color;
}
public void setRadius(double radius) {
this.radius = radius;
}
public void setColor(String color) {
this.color = color;
}

public String toString() {


return "Circle[radius=" + radius + ",color=" + color + "]";
}

public double getArea() {


return radius * radius * Math.PI;
}
}

class Cylinder extends Circle {


// private instance variable
private double height;

// Constructors
public Cylinder() {
super(); // invoke superclass' constructor Circle()
this.height = 1.0;
System.out.println("Constructed a Cylinder with Cylinder()"); // for debugging
}
public Cylinder(double height) {
super(); // invoke superclass' constructor Circle()
this.height = height;
System.out.println("Constructed a Cylinder with Cylinder(height)"); // for debugging
}
public Cylinder(double height, double radius) {
super(radius); // invoke superclass' constructor Circle(radius)
this.height = height;
System.out.println("Constructed a Cylinder with Cylinder(height, radius)"); // for debugging
}
public Cylinder(double height, double radius, String color) {
super(radius, color); // invoke superclass' constructor Circle(radius, color)
this.height = height;
System.out.println("Constructed a Cylinder with Cylinder(height, radius, color)"); // for
debugging
}

public double getHeight() {


return this.height;
}
public void setHeight(double height) {
this.height = height;
}

public double getVolume() {


return getArea()*height; // Use Circle's getArea()
}

public String toString() {


return "This is a Cylinder"; // to be refined later
}
}

public class Main {


public static void main(String[] args) {
Cylinder cy1 = new Cylinder();
//Construced a Circle with Circle()
//Constructed a Cylinder with Cylinder()
System.out.println("Radius is " + cy1.getRadius()
+ ", Height is " + cy1.getHeight()
+ ", Color is " + cy1.getColor()
+ ", Base area is " + cy1.getArea()
+ ", Volume is " + cy1.getVolume());

Cylinder cy2 = new Cylinder(5.0, 2.0);


System.out.println("Radius is " + cy2.getRadius()
+ ", Height is " + cy2.getHeight()
+ ", Color is " + cy2.getColor()
+ ", Base area is " + cy2.getArea()
+ ", Volume is " + cy2.getVolume());
}
}
class Person {
// private instance variables
private String name, address;

/** Constructs a Person instance with the given name and address */
public Person(String name, String address) {
this.name = name;
this.address = address;
}

// Getters and Setters


/** Returns the name */
public String getName() {
return name;
}
/** Returns the address */
public String getAddress() {
return address;
}
/** Sets the address */
public void setAddress(String address) {
this.address = address;
}

/** Returns a self-descriptive string */


@Override
public String toString() {
return name + "(" + address + ")";
}
}

class Student extends Person {


// private instance variables
private int numCourses; // number of courses taken so far
private String[] courses; // course codes
private int[] grades; // grade for the corresponding course codes
private static final int MAX_COURSES = 30; // maximum number of courses

/** Constructs a Student instance with the given name and address */
public Student(String name, String address) {
super(name, address);
numCourses = 0;
courses = new String[MAX_COURSES];
grades = new int[MAX_COURSES];
}

/** Returns a self-descriptive string */


@Override
public String toString() {
return "Student: " + super.toString();
}

/** Adds a course and its grade - No input validation */


public void addCourseGrade(String course, int grade) {
courses[numCourses] = course;
grades[numCourses] = grade;
++numCourses;
}

/** Prints all courses taken and their grade */


public void printGrades() {
System.out.print(this);
for (int i = 0; i < numCourses; ++i) {
System.out.print(" " + courses[i] + ":" + grades[i]);
}
System.out.println();
}

/** Computes the average grade */


public double getAverageGrade() {
int sum = 0;
for (int i = 0; i < numCourses; i++ ) {
sum += grades[i];
}
return (double)sum/numCourses;
}
}
class Teacher extends Person {
// private instance variables
private int numCourses; // number of courses taught currently
private String[] courses; // course codes
private static final int MAX_COURSES = 5; // maximum courses

/** Constructs a Teacher instance with the given name and address */
public Teacher(String name, String address) {
super(name, address);
numCourses = 0;
courses = new String[MAX_COURSES];
}

/** Returns a self-descriptive string */


@Override
public String toString() {
return "Teacher: " + super.toString();
}

/** Adds a course. Returns false if the course has already existed */
public boolean addCourse(String course) {
// Check if the course already in the course list
for (int i = 0; i < numCourses; i++) {
if (courses[i].equals(course)) return false;
}
courses[numCourses] = course;
numCourses++;
return true;
}

/** Removes a course. Returns false if the course cannot be found in the course list */
public boolean removeCourse(String course) {
boolean found = false;
// Look for the course index
int courseIndex = -1; // need to initialize
for (int i = 0; i < numCourses; i++) {
if (courses[i].equals(course)) {
courseIndex = i;
found = true;
break;
}
}
if (found) {
// Remove the course and re-arrange for courses array
for (int i = courseIndex; i < numCourses-1; i++) {
courses[i] = courses[i+1];
}
numCourses--;
return true;
} else {
return false;
}
}
}

public class Main {


public static void main(String[] args) {
/* Test Student class */
Student s1 = new Student("Tan Ah Teck", "1 Happy Ave");
s1.addCourseGrade("IM101", 97);
s1.addCourseGrade("IM102", 68);
s1.printGrades();
//Student: Tan Ah Teck(1 Happy Ave) IM101:97 IM102:68
System.out.println("Average is " + s1.getAverageGrade());
//Average is 82.5

/* Test Teacher class */


Teacher t1 = new Teacher("Paul Tan", "8 sunset way");
System.out.println(t1);
//Teacher: Paul Tan(8 sunset way)
String[] courses = {"IM101", "IM102", "IM101"};
for (String course: courses) {
if (t1.addCourse(course)) {
System.out.println(course + " added");
} else {
System.out.println(course + " cannot be added");
}
}

for (String course: courses) {


if (t1.removeCourse(course)) {
System.out.println(course + " removed");
} else {
System.out.println(course + " cannot be removed");
}
}

}
}
class SimpleGeometricObject {
private String color = "white";
private boolean filled;
private java.util.Date dateCreated;

/** Construct a default geometric object */


public SimpleGeometricObject() {
dateCreated = new java.util.Date();
}

/** Construct a geometric object with the specified color


* and filled value */
public SimpleGeometricObject(String color, boolean filled) {
dateCreated = new java.util.Date();
this.color = color;
this.filled = filled;
}

/** Return color */


public String getColor() {
return color;
}

/** Set a new color */


public void setColor(String color) {
this.color = color;
}

/** Return filled. Since filled is boolean,


its get method is named isFilled */
public boolean isFilled() {
return filled;
}

/** Set a new filled */


public void setFilled(boolean filled) {
this.filled = filled;
}

/** Get dateCreated */


public java.util.Date getDateCreated() {
return dateCreated;
}

/** Return a string representation of this object */


public String toString() {
return "created on " + dateCreated + "\ncolor: " + color +
" and filled: " + filled;
}
}

class CircleFromSimpleGeometricObject
extends SimpleGeometricObject {
private double radius;

public CircleFromSimpleGeometricObject() {
}

public CircleFromSimpleGeometricObject(double radius) {


this.radius = radius;
}

public CircleFromSimpleGeometricObject(double radius,


String color, boolean filled) {
this.radius = radius;
setColor(color);
setFilled(filled);
}

/** Return radius */


public double getRadius() {
return radius;
}

/** Set a new radius */


public void setRadius(double radius) {
this.radius = radius;
}

/** Return area */


public double getArea() {
return radius * radius * Math.PI;
}

/** Return diameter */


public double getDiameter() {
return 2 * radius;
}
/** Return perimeter */
public double getPerimeter() {
return 2 * radius * Math.PI;
}

/* Print the circle info */


public void printCircle() {
System.out.println("The circle is created " + getDateCreated() +
" and the radius is " + radius);
}
}

class RectangleFromSimpleGeometricObject
extends SimpleGeometricObject {
private double width;
private double height;

public RectangleFromSimpleGeometricObject() {
}

public RectangleFromSimpleGeometricObject(
double width, double height) {
this.width = width;
this.height = height;
}

public RectangleFromSimpleGeometricObject(
double width, double height, String color, boolean filled) {
this.width = width;
this.height = height;
setColor(color);
setFilled(filled);
}

/** Return width */


public double getWidth() {
return width;
}

/** Set a new width */


public void setWidth(double width) {
this.width = width;
}

/** Return height */


public double getHeight() {
return height;
}

/** Set a new height */


public void setHeight(double height) {
this.height = height;
}

/** Return area */


public double getArea() {
return width * height;
}

/** Return perimeter */


public double getPerimeter() {
return 2 * (width + height);
}
}

class Main {
public static void main(String[] args) {
CircleFromSimpleGeometricObject circle =
new CircleFromSimpleGeometricObject(1);
System.out.println("A circle " + circle.toString());
System.out.println("The color is " + circle.getColor());
System.out.println("The radius is " + circle.getRadius());
System.out.println("The area is " + circle.getArea());
System.out.println("The diameter is " + circle.getDiameter());

RectangleFromSimpleGeometricObject rectangle =
new RectangleFromSimpleGeometricObject(2, 4);
System.out.println("\nA rectangle " + rectangle.toString());
System.out.println("The area is " + rectangle.getArea());
System.out.println("The perimeter is " +
rectangle.getPerimeter());
}
}
class Author {
private String name;
private String email;
private char gender; // 'm' or 'f'

public Author(String name, String email, char gender) {


this.name = name;
this.email = email;
this.gender = gender;
}
public String getName() {
return name;
}
public char getGender() {
return gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}

public String toString() {


return name + " (" + gender + ") at " + email;
}
}

class Book {
private String name;
private Author author;
private double price;
private int qty;

public Book(String name, Author author, double price, int qty) {


this.name = name;
this.author = author;
this.price = price;
this.qty = qty;
}

public String getName() {


return name;
}
public Author getAuthor() {
return author; // return member author, which is an instance of the class Author
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}

public String toString() {


return "'" + name + "' by " + author; // author.toString()
}
}

public class Main {


public static void main(String[] args) {
Author a1 = new Author("abc", "abc@a.com", 'm');
System.out.println(a1); // Author's toString()
Book b1 = new Book("Java for dummies", a1, 9.99, 999);
System.out.println(b1); // Book's toString()

b1.setPrice(18.88);
b1.setQty(8);
System.out.println("name is: " + b1.getName());
System.out.println("price is: " + b1.getPrice());
System.out.println("qty is: " + b1.getQty());
System.out.println("author is: " + b1.getAuthor()); // invoke Author's toString()
System.out.println("author's name is: " + b1.getAuthor().getName());
System.out.println("author's email is: " + b1.getAuthor().getEmail());
System.out.println("author's gender is: " + b1.getAuthor().getGender());

Book b2 = new Book("Java for more dummies",


new Author("Peter Lee", "p@abc.com", 'm'), // an anonymous Author's instance
19.99, 18);
System.out.println(b2); // Book's toString()
}
}

You might also like