Showing posts with label class. Show all posts
Showing posts with label class. Show all posts

Thursday, September 15, 2011

Overriding Methods

A derived class (Tiger) can override methods of a base class (Cat). The overridden methods are called even when a reference to an instance of the derived class (tiger1) is stored in a variable of the base class (cat2).

browse

package org.megha.blog.example.part7;

public class Cat {

    public String whoAmI() {
        return "I am a cat.";
    }
}

package org.megha.blog.example.part7;

public class Tiger extends Cat {
// a tiger is also a cat :)

    @Override
    public String whoAmI() {
        return "I am a tiger.";
    }
}

package org.megha.blog.example.part7;

public class Main {

    public static void main(String args[]) {

        Cat cat1 = new Cat();
        Tiger tiger1 = new Tiger();
        Cat cat2 = tiger1;

        System.out.println(cat1.whoAmI());
        // prints "I am a cat."

        System.out.println(tiger1.whoAmI());
        // prints "I am a tiger."

        System.out.println(cat2.whoAmI());
        // prints "I am a tiger."
    }
}

Abstract Classes

An abstract class for a three dimensional object (ThreeDObject) and two concrete classes (Sphere and Cylinder) derived from that abstract class. The abstract class defines the method getSurfaceToVolumeRatio() which uses the abstract methods getSurfaceArea() and getVolume(). Any ThreeDObject derived class can have it's own mechanism to calculate surface area and volume.

browse

package org.megha.blog.example.part6;

/** 
 * A 3-Dimensional object, which has a surface area, volume and
 * a surface area to volume ratio. This abstract class has a
 * concrete surface-area to volume ratio method implementation
 * which depends on the object specific surface-area and volume
 * definitions.
 */
public abstract class ThreeDObject {

    public abstract double getSurfaceArea();
    public abstract double getVolume();

    public double getSurfaceToVolumeRatio() {
        return getSurfaceArea()/getVolume();
    }
}

package org.megha.blog.example.part6;

/** A sphere with a volume and surface area */
public class Sphere extends ThreeDObject {

    double radius;

    public Sphere(double radius) {
        this.radius = radius;
    }

    @Override
    public double getSurfaceArea() {
        return (4 * Math.PI * radius * radius);
    }

    @Override
    public double getVolume() {
        // note that doing 4 / 3 * Math.PI * radius * radius * radius
        // yields a differnt result as
        // 4 / 3 (integer division) equals 1
                return (4 * Math.PI * radius * radius * radius) / 3;
        }

        @Override
        public String toString() {
                return "sphere radius(" + radius + ")";
        }
}

package org.megha.blog.example.part6;

/** A Cylinder 3-D object */
public class Cylinder extends ThreeDObject {

    private double height;
    private double radius;

    public Cylinder(double height, double radius) {
        this.height = height;
        this.radius = radius;
    }

    @Override
    public double getSurfaceArea() {
           return 2 * Math.PI * radius * (radius + height);
    }

    @Override
    public double getVolume() {
        return Math.PI * radius * radius * height;
    }

    @Override
    public String toString() {
        return "cylinder radius(" + radius + "), height(" + height + ")";
    }
}

package org.megha.blog.example.part6;

/** Creates some ThreeDObjects and prints their details */
public class Main {

    private static void printSurfaceAreaRatio(ThreeDObject obj) {
        System.out.println("------------------");
        System.out.println("for object " + obj);
        System.out.println("surface area " + obj.getSurfaceArea());
        System.out.println("volume " + obj.getVolume());
        System.out.println("surface area to volume ratio " + obj.getSurfaceToVolumeRatio());
    }

    public static void main(String args[]) {
        printSurfaceAreaRatio(new Sphere(1));
        printSurfaceAreaRatio(new Sphere(2));
        printSurfaceAreaRatio(new Cylinder(1, 1));
        printSurfaceAreaRatio(new Cylinder(1, 2));
        printSurfaceAreaRatio(new Cylinder(2, 1));
        printSurfaceAreaRatio(new Cylinder(2, 2));
    }
}

Interfaces

Here's an example to show how an interface (Shape) is defined, implemented (Square, Circle) and used (Main). Note: how Object.toString() is overriden and is used by printInfo()

browse

package org.megha.blog.example.part5;

/** An Interface for a shape that has an area and a perimeter */
public interface Shape {
	public double area();
	public double perimeter();
}

package org.megha.blog.example.part5;

/** A class that represents a circle */
public class Circle implements Shape {

	double radius;

	public Circle(double radius) {
		this.radius = radius;
	}

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

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

	@Override
	public String toString() {
		return "circle of radius " + radius;
	}
}

package org.megha.blog.example.part5;

/** A square shape */
public class Square implements Shape {

	private double side;

	public Square(double side) {
		this.side = side;
	}

	public double area() {
		return side * side;
	}

	public double perimeter() {
		return 4 * side;
	}

	@Override
	public String toString() {
		return "square of side " + side;
	}
}

package org.megha.blog.example.part5;

/** Creates a square and a circle and prints their area and perimeter */
public class Main {

	private static void printInfo(Shape s) {
		System.out.println("for shape: " + s);
		System.out.println("area: " + s.area());
		System.out.println("perimeter: " + s.perimeter());
	}

	public static void main(String args[]) {
		Square square1 = new Square(5);
		printInfo(square1);

		Circle circle1 = new Circle(7);
		printInfo(circle1);
	}
}
Output of this program:
for shape: square of side 5.0
area: 25.0
perimeter: 20.0
for shape: circle of radius 7.0
area: 153.93804002589985
perimeter: 43.982297150257104

Overloaded Constructors

Here's how we can overload constructors - and use any one of them at create time.

browse

package org.megha.blog.example.part3;

/**
 * Represents a person, with a name and a title.
 */
public class Person {

	private String name;
	private String title;

	/** creates a {@link Person} with a name and a title */
	public Person(String name, String title) {
		this.name = name;
		this.title = title;
	}

	/** creates a {@link Person} with only a name (title is set to UNKNOWN) */
	public Person(String name) {
		this(name, "UNKNOWN"); // calls the previous constructor
                                       // with title as UNKNOWN
	}

	/** creates a {@link Person} without a name or a title */
	public Person() {
		this("NO_NAME"); 
                // note how the one-arg constructor is called, 
                // which calls the two arg constructor
	}

	public void print() {
		System.out.println("----------------------");
		System.out.println("Name = " + name);
		System.out.println("Title = " + title);
	}

	public static void main(String args[]) {
		// Person class has overloaded constructors,
                // and we can call any of these.
		Person person1 = new Person();
		Person person2 = new Person("Sam");
		Person person3 = new Person("Sam","Engineer");

		person1.print();
		person2.print();
		person3.print();
	}
}
Output of this program:
----------------------
Name = NO_NAME
Title = UNKNOWN
----------------------
Name = Sam
Title = UNKNOWN
----------------------
Name = Sam
Title = Engineer

Instantiation

This program shows how you create an object/instance of a class, and call methods in the created object.

browse

package org.megha.blog.example.part2;

/**
 * A Circle that can calculate it's area and perimeter.
 */
public class Circle {

	private double radius;

	/** 
	 * Constructor to create a circle of a given radius.
	 * Note: how you cannot create a Circle without specifying it's radius!
	 */
	public Circle(double radius) {
		this.radius = radius;
	}

	/** @return the radius of the circle */
	public double getRadius() {
		return radius;
	}

	/** @return the area of a circle (PI*r*r) */
	public double getArea() {
		double area = Math.PI*radius*radius;
		return area;
	}

	/** @return the perimeter of the circle (2*PI*r) */
	public double getPerimeter() {
		double perimeter = 2 * Math.PI * radius;
		return perimeter;
	}

	/** prints the radius, area and perimeter of this circle */
	public void print() {
		System.out.println("Circle, with radius  " + getRadius());
		System.out.println("Area = " + getArea());
		System.out.println("Perimeter = " + getPerimeter());
	}

	public static void main(String args[]) {
		// create a circle of radius 10
		Circle circle1 = new Circle(10);
		// print information about the circle we just created
		circle1.print();
	}
}