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

M3 Inheritance Copy

Uploaded by

C.M Srinivas
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

M3 Inheritance Copy

Uploaded by

C.M Srinivas
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 26

M3-Inheritance

• It is possible to inherit attributes and methods from one class to


another. We group the "inheritance concept" into two categories:
• subclass (child) - the class that inherits from another class
• superclass (parent) - the class being inherited from
• To inherit from a class, use the extends keyword.

• class DerivedClass extends BaseClass


{
//methods and fields
•}
• class Vehicle {
• protected String brand = "Ford";
• public void honk() {
• System.out.println(“ford sound!");
• }
• }
• class Car extends Vehicle {
• private String modelName = "Mustang";
• public static void main(String[] args) {
• Car myFastCar = new Car();
• myFastCar.honk();
• System.out.println(myFastCar.brand + " " + myFastCar.modelName);
• }
• }
• // Create a superclass.
• class A {
• int i, j;
• void showij() {
• System.out.println("i and j: " + i + " " + j); }
•}
• // Create a subclass by extending class A. class B extends A { int k;
void showk() { System.out.println("k: " + k); }
• void sum() { System.out.println("i+j+k: " + (i+j+k)); } }
• class SimpleInheritance {
• public static void main(String[] args) {
• A superOb = new A();
• B subOb = new B(); // The superclass may be used by itself.
• superOb.i = 10;
• superOb.j = 20; S
• ystem.out.println("Contents of superOb: ");
• superOb.showij();
• System.out.println(); /* The subclass has access to all public members of its superclass. */
• subOb.i = 7; subOb.j = 8; subOb.k = 9;
• System.out.println("Contents of subOb: ");
• subOb.showij();
• subOb.showk();
• System.out.println();
• System.out.println("Sum of i, j and k in subOb:");
• subOb.sum(); } }
The output from this program is
shown here:
• Contents of superOb: i and j: 10 20 Contents of subOb: i and j: 7 8 k: 9
Sum of i, j and k in subOb: i+j+k: 24
Member Access and Inheritance
• Although a subclass includes all of the members of its superclass, it
cannot access those members of the superclass that have been
declared as private.
• // Create a superclass.
• class A {
• int i; // default access
• private int j; // private to A
• void setij(int x, int y)
• { i = x; j = y; }
•}
• // A's j is not accessible here.
• class B extends A {
• int total;
• void sum()
• {
• total = i + j; // ERROR, j is not accessible here
• }}
• public static void main(String[] args) {
• B subOb = new B();
• subOb.setij(10, 12);
• subOb.sum();
• System.out.println("Total is " + subOb.total);
• }
• ERROR: This program will not compile because the use of j inside the sum( ) method of B
causes an access violation. Since j is declared as private, it is only accessible by other
members of its own class. Subclasses have no access to it.
• // This program uses inheritance to extend Box.
• class Box {
• double width; double height; double depth;
• // construct clone of an object
• Box(Box ob) {
• // pass object to constructor
• width = ob.width;
• height = ob.height;
• depth = ob.depth;
• }
• // constructor used when all dimensions specified
• Box(double w, double h, double d)
• { width = w; height = h; depth = d; }
• // constructor used when no dimensions specified
• Box() {
• width = -1; // use -1 to indicate an uninitialized box
• height = -1;
• depth = -1;
•}
• // constructor used when cube is created
• Box(double len) {
• width = height = depth = len; }
• // compute and return volume
• double volume()
• { return width * height * depth;
• }}
• // Here, Box is extended to include weight.
• class BoxWeight extends Box {
• double weight; // weight of box
• // constructor for BoxWeight
• BoxWeight(double w, double h, double d, double m)
• { width = w; height = h; depth = d; weight = m; } }
public static void main(String[] args) {
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol); System.out.println("Weight of
mybox1 is " + mybox1.weight); System.out.println(); vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol); System.out.println("Weight of
mybox2 is " + mybox2.weight);
}
The output from this program is :
Volume of mybox1 is 3000.0
Weight of mybox1 is 34.3
Volume of mybox2 is 24.0
Weight of mybox2 is 0.076
A Superclass Variable Can Reference a
Subclass Object
• A reference variable of a superclass can be assigned a reference to any
subclass derived from that superclass.
• public static void main(String[] args) {
• BoxWeight weightbox = new BoxWeight(3, 5, 7, 8.37);
• Box plainbox = new Box();
• double vol; vol = weightbox.volume();
• System.out.println("Volume of weightbox is " + vol);
System.out.println("Weight of weightbox is " + weightbox.weight);
System.out.println();
• plainbox = weightbox; // assign BoxWeight reference to Box reference
• vol = plainbox.volume(); // volume() defined in Box
System.out.println("Volume of plainbox is " + vol);
Using super

• Whenever a subclass needs to refer to its immediate superclass, it can do so


by use of the keyword super.
• super has two general forms.
• The first calls the superclass’ constructor.
• The second is used to access a member of the superclass that has been
hidden by a member of a subclass.
Using super to Call Superclass Constructors:
A subclass can call a constructor defined by its superclass by use of the
following form of super: super(arg-list);
Here, arg-list specifies any arguments needed by the constructor in the
superclass.
super( ) must always be the first statement executed inside a subclass’
constructor.
Using super to Call Superclass Constructors
• class Animal{
• Animal(){System.out.println("animal is created");}
• }
• class Dog extends Animal{
• Dog(){
• super();
• System.out.println("dog is created");
• }
• }
• class TestSuper3{
• public static void main(String args[]){
• Dog d=new Dog();
• }}
OUTPUT:
• animal is created
super can be used to invoke parent class method
• The super keyword can also be used to invoke parent class method. It should be used if subclass contains the
same method as parent class. In other words, it is used if method is overridden.
• class Animal{
• void eat() {System.out.println("eating...");}
• }
• class Dog extends Animal{
• void eat() {System.out.println("eating bread...");}
• void bark() {System.out.println("barking...");}
• void work() {
• super.eat(); //method is overridden.
• bark(); } }
• class TestSuper2{
• public static void main(String args[]){
• Dog d=new Dog();
• d.work();}}

• OUTPUT:
• eating...
• barking...
A Second Use for super is used to refer immediate parent
class instance variable.
The second form of super acts somewhat like this, except that it always refers to the superclass of
the subclass in which it is used. This usage has the following general form: super.member
member can be either a method or an instance variable.

class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color); //prints color of Dog class
System.out.println(super.color); //prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
Creating a Multilevel Hierarchy
class A {
void funcA() {
System.out.println("This is class A"); } }
class B extends A {
void funcB() { System.out.println("This is class B");
} }
class C extends B { void funcC() {
System.out.println("This is class C"); } }
public class Demo {
public static void main(String args[]) {
C obj = new C();
obj.funcA();
obj.funcB();
obj.funcC();
} }
When Constructors Are Executed
• // Create a super class.
class A {
A() { System.out.println("Inside A's constructor."); } }
// Create a subclass by extending class A.
class B extends A {
B() { System.out.println("Inside B's constructor."); } }
// Create another subclass by extending B.
class C extends B {
C() { System.out.println("Inside C's constructor."); } }
• class CallingCons {
• public static void main(String[] args) {
• C c = new C();
• }
• }
• Output:
• The output from this program is shown here:
• Inside A's constructor
• Inside B's constructor
• Inside C's constructor
• Note:the constructors are executed in order of derivation.
• Overriding is a feature that allows a subclass or child class to provide a
specific implementation of a method that is already provided by one
of its super-classes or parent classes.
• Method overriding occurs only when the names and the type
signatures of the two methods are identical.
• Method overriding is one of the ways by which Java achieves
Run Time Polymorphism.
Java program to demonstrate method overriding in java
// Base Class
class Parent {
void show()
{ System.out.println("Parent's show()"); } }
// Inherited class
class Child extends Parent {
// This method overrides show() of Parent
@Override void show() {
System.out.println("Child's show()"); } }
// Driver class
class Main { public static void main(String[] args) {
// If a Parent type reference refers // to a Parent object, then Parent's //
show is called
Parent obj1 = new Parent();
obj1.show(); // If a Parent type reference refers // to a Child object Child's
show() // is called. This is called RUN TIME // POLYMORPHISM.
Parent obj2 = new Child(); obj2.show(); } }
Create three sub classes
namely: circle, triangle and square, each class has two
member functions named
draw () and erase (). Demonstrate polymorphism concepts
by developing suitable
methods, defining member data and main program.
• class Shape { // Member functions
• public void draw()
• { System.out.println("Drawing a shape"); }
• public void erase() {
• System.out.println("Erasing a shape"); }}
• // Circle class, a subclass of Shape
• class Circle extends Shape {
• public void draw1() { System.out.println("Drawing a circle"); }
• public void erase1() { System.out.println("Erasing a circle"); }}
• // Triangle class, a subclass of Shape
• class Triangle extends Shape {
• public void draw2() { System.out.println("Drawing a triangle"); }
public void erase2() { System.out.println("Erasing a triangle"); }}
• class Square extends Shape{
• public void draw3() {
• System.out.println("Drawing a square"); }
• public void erase3() { System.out.println("Erasing a square"); }}
• // Main program to demonstrate polymorphism
• class Main{
• public static void main(String[] args) {
• // Creating objects of different shapes
• Circle c = new Circle();
• Triangle t = new Triangle();
• Square s = new Square(); // Demonstrating polymorphism by calling
//draw and erase methods
• System.out.println("Using Circle object:"); c.draw(); c.erase();
System.out.println("\nUsing Triangle object:"); t.draw(); t.erase();
System.out.println("\nUsing Square object:"); s.draw(); s.erase(); }}
OUTPUT
• Using Circle object:
• Drawing a shape
• Erasing a shape

• Using Triangle object:


• Drawing a shape
• Erasing a shape

• Using Square object:


• Drawing a shape
• Erasing a shape

You might also like