PDA

View Full Version : Most basic example of Inheritance.


javaguru
07-02-2010, 08:51 AM
class A {
int m, n;
void display1() {
System.out.println("m and n are "+m+" "+n);
}
}
class B extends A {
int c;
void display2() {
System.out.println("c:"+c);
}
void sum() {
System.out.println("m+n+c"+(m+n+c));
}
}
public class InheritanceDemo {
public static void main(String args[]) {
A s1 = new A();
B s2 = new B();
s1.m = 10;
s1.n = 20;
System.out.println("State of Object A:");
s1.display1();
s2.m = 7;
s2.n = 8;
s2.c = 9;
System.out.println("State of Object B:");
s2.display1();
s2.display2();
System.out.println("sum of m, n and c in Object B is:");
s2.sum();
}
}

javaguru
07-02-2010, 09:00 AM
The output will be

Sate of Object A:
m and n are 10 20
State of Object B:
m and n are 7 8
c:9
sum of m, n and c in Object B is:
m+n+c24

slicegan2
12-08-2010, 05:39 PM
This example features a simple way to perform inheritance. It creates a class called Circle that contains calculations for a circle based on its radius. It calculates the diameter, the circumference, and the area. Then, a class called Sphere inherits from the Circle class:
Source File: Circle.cs

namespace FlatShapes
{
class Circle
{
private double _radius;

public double Radius
{
get { return (_radius < 0) ? 0.00 : _radius; }
set { _radius = value; }
}
public double Diameter
{
get { return Radius * 2; }
}
public double Circumference
{
get { return Diameter * 3.14159; }
}
public double Area
{
get { return Radius * Radius * 3.14159; }
}
}
}
=========================

chairs (http://www.officechairsuk.com) | office chairs (http://www.officechairsuk.com/office_chairs.html)