0% found this document useful (0 votes)
17 views105 pages

Unit 2

This document covers key concepts in Java programming, focusing on methods, classes, and inheritance. It explains access modifiers, argument passing, method overloading, recursion, static members, and nested classes. Additionally, it provides examples to illustrate these concepts in practice.

Uploaded by

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

Unit 2

This document covers key concepts in Java programming, focusing on methods, classes, and inheritance. It explains access modifiers, argument passing, method overloading, recursion, static members, and nested classes. Additionally, it provides examples to illustrate these concepts in practice.

Uploaded by

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

PROGRAMMING WITH JAVA

A CLOSER LOOK AT METHOD & CLASSES

INHERITANCE BASICS
Unit-2
UNIT – II
 A Closer Look at Methods and Classes:
 Controlling Access to Class Members, Pass Objects to Methods,
How Arguments are passed, Returning Objects, Method
Overloading, Overloading Constructors, Recursion, Understanding
Static, Introducing Nested and Inner Classes, Varargs: Variable-
Length Arguments. Inheritance
 Inheritance Basics
 Member Access and Inheritance, Constructors and Inheritance,
Using super to Call Superclass constructors, Using super to Access
Superclass Members, Creating a Multilevel Hierarchy, When are
Constructors Executed, Superclass References and Subclass
Objects, Method Overriding, Overridden Methods support
polymorphism, Why Overridden Methods, Using Abstract Classes,
Using final, The Object Class.
Controlling Access to Class Members

 The support of encapsulation , the class provides two


major benefits
 Links the data with the code
 Access members can be controlled

 Private
 It can be accessed only by other methods defined by its
class
 Public
 Can be freely accessed by the code defined outside the
class
 Default
Java’s access modifiers
 Public
 Private
 Protected
 Default (if nothing specified assumes but same as
public)

public int i;
private double j;
private int myMethod(int a, char b) { //...
Example
/* This program demonstrates the difference between public and private. */
class Test {
int a; // default access
public int b; // public access
private int c; // private access
// methods to access c
void setc(int i) { // set c's value
c = i;
}
int getc()
{ // get c's value
return c;
}
}
Example
class AccessTest {
public static void main(String args[]) {
Test ob = new Test();
// These are OK, a and b may be accessed directly
ob.a = 10;
ob.b = 20;
// This is not OK and will cause an error
// ob.c = 100; // Error!
// You must access c through its methods
ob.setc(100); // OK
System.out.println("a, b, and c: " + ob.a + " " +
ob.b + " " + ob.getc());
}
}
Using Objects as Parameters
class Test {
int a, b;
Test(int i, int j) { class PassOb {
a = i; public static void main(String args[]) {
b = j; Test ob1 = new Test(100, 22);
} Test ob2 = new Test(100, 22);
boolean equalTo(Test o) { Test ob3 = new Test(-1, -1);
if(o.a == a && o.b == b) System.out.println("ob1 == ob2: " +
return true; ob1.equalTo(ob2));
else System.out.println("ob1 == ob3: " +
return false; ob1.equalTo(ob3));
} }
} }

Output:
ob1 == ob2: true
ob1 == ob3: false
A Closer Look at Argument Passing
How Arguments are Passed

 In Java, there are two ways of passing


arguments to a method.
 Call by value : This approach copies the value of an
argument into the formal parameter of the method.
Therefore, changes made to the parameter of the method
have no effect on the argument.
 Call by reference: In this approach, a reference to an
argument is passed to the parameter. Inside the
subroutine, this reference is used to access the actual
argument specified in the call. This means that changes
made to the parameter will affect the argument used to
call the subroutine.
Example
class Test class CallByRef
{ int a, b; {
Test(int i, int j) public static void main(String args[])
{ {
a = i; b = j;
} Test ob = new Test(15, 20);
void meth(Test o) System.out.println("before call: " + ob.a + " " +
{ ob.b); ob.meth(ob);
o.a*= 2; System.out.println("after call: " + ob.a + " " +
o.b/= 2; ob.b);
} }
} }

Output:
before call: 15 20
after call: 30 10
Returning the Objects
 A method can return any type of data
 Include the class object then its called the returning
the class object
class Test {
int a;
Test(int i) {
a = i;
}
Test incrByTen() {
Test temp = new Test(a+10);
return temp;
}
}
Example
class RetOb {
public static void main(String args[]) {
Test ob1 = new Test(2);
Test ob2;
ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);
ob2 = ob2.incrByTen();
System.out.println("ob2.a after second increase: “ + ob2.a);
}
}

The output generated by this program is shown here:


ob1.a: 2
ob2.a: 12
ob2.a after second increase: 22
Methods Overloading
 Method overloading is one of the ways that Java supports
polymorphism.
 When an overloaded method is invoked, Java uses the type and/or
number of arguments as its guide to determine which version of the
overloaded method to actually call.
 Thus, overloaded methods must differ in the type and/or number of
their parameters.
 While overloaded methods may have different return types, the
return type alone is insufficient to distinguish two versions of a
method.
 When Java encounters a call to an overloaded method, it simply
executes the version of the method whose parameters match the
arguments used in the call.
Method Overloading
class OverloadDemo { class Overload {
void test() { public static void main(String args[]) {
System.out.println("No parameters"); OverloadDemo ob = new
} OverloadDemo();
void test(int a) { double result;
System.out.println("a: " + a); // call all versions of test()
} ob.test();
void test(int a, int b) { ob.test(10);
System.out.println("a and b: " + a + " " + b); ob.test(10, 20);
} result = ob.test(123.25);
double test(double a) { System.out.println("Result of
System.out.println("double a: " + a); ob.test(123.25): " + result);
return a*a; }
} }
}
No parameters
a: 10
a and b: 10 20 double a: 123.25
Result of ob.test(123.25): 15190.5625
Example
// Automatic type conversions apply class Overload {
to overloading. public static void main(String args[]) {
class OverloadDemo { OverloadDemo ob = new
void test() { OverloadDemo();
System.out.println("No parameters"); int i = 88;
} ob.test();
void test(int a, int b) { ob.test(10, 20);
System.out.println("a and b: " + a + " ob.test(i); // this will invoke test(double)
" + b); ob.test(123.2); // this will invoke
} test(double)
void test(double a) { }
System.out.println("Inside test(double) }
a: " + a);
} No parameters
} a and b: 10 20
Inside test(double) a: 88
Inside test(double) a: 123.2
Overloading Constructors
 In addition to overloading normal methods,
 We can also overload constructor methods.
 In fact, for most real-world classes that you create,
overloaded constructors will be the norm, not the
exception.
Example
/* Here, Box defines three // constructor used when no dimensions
constructors to initialize specified
the dimensions of a box various Box() {
ways. width = -1; // use -1 to indicate
*/ height = -1; // an uninitialized
class Box { depth = -1; // box
double width; }
double height; // constructor used when cube is created
double depth; Box(double len) {
Box(double w, double h, double d) { width = height = depth = len;
width = w; }
height = h; // compute and return volume
depth = d; double volume() {
} return width * height * depth;
}
}
Example
class OverloadCons {
public static void main(String args[]) {
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
Volume of mycube is 343.0
Parameter Constructor (Object)
 One of the most common uses of object parameters
involves constructors.
 Frequently, we want to construct a new object so
that it is initially the same as some existing object.
 To do this, we must define a constructor that takes
an object of its class as a parameter.
 For example, the following version of Box allows
one object to initialize another:
Example
class Box { // constructor used when no dimensions
double width; specified
double height; Box() {
double depth; width = -1; // use -1 to indicate
Box(Box ob) { height = -1; // an uninitialized
width = ob.width; depth = -1; // box
height = ob.height; depth = }
ob.depth; // constructor used when cube is created
} Box(double len) {
Box(double w, double h, double d) { width = height = depth = len;
width = w; }
height = h; // compute and return volume
depth = d; double volume() {
} return width * height * depth;
}
}
Example
class OverloadCons2 {
public static void main(String args[]) {
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
Box myclone = new Box(mybox1);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
vol = mycube.volume();
System.out.println("Volume of cube is " + vol);
vol = myclone.volume();
System.out.println("Volume of clone is " + vol); Volume of mybox1 is 3000.0
} Volume of mybox2 is -1.0
} Volume of mycube is 343.0
Volume of clone is 3000.0
Recursion
 Java supports recursion.
 Recursion is the process of defining something in
terms of itself.
 As it relates to Java programming, recursion is the
attribute that allows a method to call itself.
 A method that calls itself is said to be recursive.
Example
class Factorial { class Recursion {
// this is a recursive public static void main(String args[]) {
method Factorial f = new Factorial();
int fact(int n) { System.out.println("Factorial of 3 is " + f.fact(3));
int result; System.out.println("Factorial of 4 is " + f.fact(4));
if(n==1) return 1; System.out.println("Factorial of 5 is " + f.fact(5));
result = fact(n-1) * n; }
return result; }
}
}

Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
Understanding static
 When a member is declared static, it can be
accessed before any objects of its class are
created, and without reference to any object.
 Instance variables declared as static are global
variables.
 When objects of its class are declared, no copy of
a static variable is made.
 Instead, all instances of the class share the same
static variable.
 Methods declared as static have several
restrictions:
 They can only directly call other static methods.
 They can only directly access static data.
 They cannot refer to this or super in any way.
Example
// Demonstrate static variables, methods, and blocks.
class UseStatic {
static int a = 3;
static int b;
static void meth(int x) {
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static {
System.out.println("Static block initialized.");
b = a * 4;
} output of the program:
public static void main(String args[]) { Static block initialized.
meth(42); x = 42
} a=3
} b = 12
 Outside of the class in which they are defined, static
methods and variables can be used independently of
any object.
 For example, if you wish to call a static method from
outside its class, you can do so using the following
general form:
 classname.method( )
 A static variable can be accessed in the same way—by
use of the dot operator on the name of the class.
 This is how Java implements a controlled version of
global methods and global variables.
Example

class StaticDemo {
static int a = 42;
static int b = 99;
static void callme() {
System.out.println("a = " + a);
}
}
class StaticByName {
public static void main(String args[]) {
StaticDemo.callme();
System.out.println("b = " + StaticDemo.b);
}
}

a = 42
b = 99
Recall
 Static Method
 Directly call only static methods
 Directly access only static data

 They do not have this reference


Another Example
Class StaticBlock{ Class SDemo3{
Static double r2; Public static void main(String args[])
Static double r3; {
Static StaticBlock ob=new StaticBlock(“Inside the
{ constructor”);
System.out.println(“Inside Static Block”); System.out.println(“Sqrt 2
r2=Math.sqrt(2.0); is”+StaticBlock.r2);
r3=Math.sqrt(3.0); System.out.println(“Sqrt 3
} is”+StaticBlock.r3);
StaticBlock(String msg) }
{ }
System.out.println(msg);
}
Inside Static Block
Inside Constructor
Sqrt 2 is 1.414213
Sqrt 3 is 1.732050
Introducing Nested and Inner Classes
 It is possible to define a
class within another class;
such classes are known as
nested classes.
 The scope of a nested class
is bounded by the scope of
its enclosing class.
 The most important type of
nested class is the inner
class.
 An inner class is a non-static
nested class.
Example
// Demonstrate an inner class. class InnerClassDemo {
class Outer { public static void main(String args[]) {
int outer_x = 100; Outer outer = new Outer();
void test() { outer.test();
Inner inner = new Inner(); }
inner.display(); }
}
// this is an inner class
class Inner { class InnerClassDemo {
void display() { public static void main(String args[]) {
System.out.println("display: outer_x = " + Outer outer = new Outer();
outer_x); Outer.Inner obin = outer.new Inner();
} obin.test();
} }
} }

display: outer_x = 100


Another Example Nested or Inner Class
Class Outer{ Int max()
Int num[]; { int m=num[0]
Outer(int n[]){ for(int i=1;i<num.length;i++)
Nums=n;
if(num[i]>m)m=num[i];
}
Void analyze(){ return m; }
Inner inob=new Inner();
Systrm.out.println(“Minimum ”+inob.min()); Int avg()
Systrm.out.println(“Maximum”+inob.max()); { int m=0;
Systrm.out.println(“Average”+inob.avg()); for(int i=1;i<num.length;i++)
} m+num[i];
Class Inner{ return m/num.length; }
Int min()
}
{ int m=num[0]
for(int i=1;i<num.length;i++) }
if(num[i]<m)m=num[i];
return m; }
Example

class NestedClasssDemo {
public static void main(String args[]) {
Int x={3,2,1,5,6,9,7,8};
Outer outob=new Outer(x);
Outob.analyze();
}
}

Output
minimum-:1
Maximim:9
Average:5
Varargs: Variable-Length Arguments
 Beginning with JDK 5, Java has included a feature that
simplifies the creation of methods that need to take a
variable number of arguments. This feature is called
varargs
 it is short for variable-length arguments.
 A method that takes a variable number of arguments is
called a variable-arity method, or simply a varargs
method.
 A variable-length argument is specified by three
periods (…). For example, here is how vaTest( ) is
written using a vararg:
 static void vaTest(int ... v) {
Example-1
// Demonstrate variable-length arguments.
class VarArgs {
static void vaTest(int ... v) {
System.out.print("Number of args: " + v.length +
" Contents: ");
for(int i=0;i<v.length;i++)
System.out.print(“arg”+i+”:” + v[i]);
System.out.println();
}
public static void main(String args[])
{
vaTest(10); // 1 arg
vaTest(1, 2, 3); // 3 args
vaTest(); // no args
}
}
Example-2
// Demonstrate variable-length arguments.
class VarArgs {
static void vaTest(String msg,int ... v) {
System.out.print("Number of args: " + v.length +
" Contents: ");
for(int i=0;i<v.length;i++)
System.out.print(“arg”+i+”:” + v[i]);
System.out.println();
}
public static void main(String args[])
{
vaTest(“one”,10); // 1 arg
vaTest(“Three”,1, 2, 3); // 3 args
vaTest(“no arguments”); // no args
}
}
Points
 The varargs parameter must be at last
 Overloading varargs can be done
 Varargs and Ambiguity

int doIt(int a, int b, double c, int ... vals) {

int doIt(int a, int b, double c, int ... vals, boolean stopFlag) { // Error!
Example
class VarArgs4 {
static void vaTest(int ... v) {
System.out.print("vaTest(int ...): " +
"Number of args: " + v.length +
" Contents: ");
for(int x : v)
System.out.print(x + " ");
System.out.println();
}
static void vaTest(boolean ... v) { public static void main(String args[])
System.out.print("vaTest(boolean ...) " + {
"Number of args: " + v.length + vaTest(1, 2, 3); // OK
" Contents: ");
vaTest(true, false, false); // OK
for(boolean x : v)
vaTest(); // Error: Ambiguous!
System.out.print(x + " ");
}
System.out.println();
} }
Inheritance Basics
Inheritance
 Inheritance in Java is a mechanism in which one
object acquires all the properties and behaviours of
parent object.
 The idea behind inheritance in Java is that you can
create new classes that are built upon existing
classes.
 Reuse methods and fields of the parent class.
 Inheritance represents the IS-A relationship which is
also known as a parent-child relationship.
 Terms used in Inheritance
 Class: A class is a group of objects which have common
properties. It is a template or blueprint from which objects are
created.
 Sub Class/Child Class: Subclass is a class which inherits the other
class. It is also called a derived class, extended class, or child
class.
 Super Class/Parent Class: Superclass is the class from where a
subclass inherits the features. It is also called a base class or a
parent class.
 Reusability: As the name specifies, reusability is a mechanism
which facilitates you to reuse the fields and methods of the
existing class when you create a new class.
class Subclass-name extends Superclass-name
{
//methods and fields
}
Example
class A { class SimpleInheritance {
int i, j; public static void main(String args []) {
void showij() { A superOb = new A();
System.out.println("i and j: " + i + " " + j); B subOb = new B();
} superOb.i = 10; superOb.j = 20;
} System.out.println("Contents of superOb: ");
superOb.showij();
class B extends A { System.out.println();
int k; subOb.i = 7; subOb.j = 8;
void showk() { subOb.k = 9;
System.out.println("k: " + k); System.out.println("Contents of subOb: ");
} subOb.showij(); subOb.showk();
void sum() { System.out.println();
System.out.println("i+j+k: " + (i+j+k)); System.out.println("Sum of i, j and k in
} subOb:");
} subOb.sum();
}
}
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
Example – Inheritance
Class TwoDShape{
double w;
double h;
void showdim(){
System.out.println(“Width and Heigth are” +w + “and”+h);
}
}

Class Triangle extends TwoDShape{


String style;
double area(){
return (w*h)/2;
}
void showstyle{
System.out.println(“Triangle is”+style);}
}
Class Shape{
{
Public static void main(String args[]){
Triangle t1=new Triangle();
Triangle t2=new Triangle();
t1.w=4.0; t1.h=4.0; t1.style=“Filled”;
t2.w=8.0; t2.h=12.0; t2.style=“outlined”;
System.out.println(“T1”);
t1.showstyle(); t1.showdim();
System.out.println(“Area”+t1.area());
System.out.println(“T2”);
t2.showstyle(); t2.showdim();
System.out.println(“Area”+t2.area());
}
}
Types of Inheritance
Using Interfaces
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.
 Can access private data members using the public
or default member functions
 Note
 All the private member functions or data members are
not inherited
Example – Inheritance data Members
are Private
Class TwoDShape{
Private double w;
Private double h;
double getwidth(){ return w};
double getheigth(){ return h};
void setwidth(double w1){w=w1};
void setheigth(double h1){h=h1};
void showdim(){
System.out.println(“Width and Heigth are” +w + “and”+h);
}
}
Class Shape{
Class Triangle extends TwoDShape{
{
String style; Public static void main(String args[]){
double area(){ Triangle t1=new Triangle();
return getwidth()* getheigth()/2; Triangle t2=new Triangle();
} t1.setwidth(4.0); t1.sewtheigth(4.0);
void showstyle{ t1.style=“Filled”;
System.out.println(“Triangle t2.w=8.0; t2.h=12.0; t2.style=“outlined”;
is”+style);} System.out.println(“T1”);
t1.showstyle(); t1.showdim();
}
System.out.println(“Area”+t1.area());
System.out.println(“T2”);
t2.showstyle(); t2.showdim();
System.out.println(“Area”+t2.area());
}
}
Constructors and Inheritance
 When a class hierarchy is created, in what order
are the constructors for the classes that make up the
hierarchy executed
 Default Constructor
 The Compile will take care of calling the constructors
 Parameter Constructor
 Its User responsible to use the constructor
 It can be done using Super keyword
Demonstrate when are constructors
executed
// Create a super class. // Create another subclass by extending B.
class A { class C extends B {
A() { C() {
System.out.println("Inside A's System.out.println("Inside C's constructor.");
constructor."); }
} }
} class CallingCons {
// Create a subclass by extending class public static void main(String args[]) {
A. C c = new C();
class B extends A { }
B() { }
System.out.println("Inside B's
constructor.");
}
} Inside A's constructor
Inside B's constructor
Inside C's constructor
Using super to call superclass
Constructor
Class TwoDShape{
Private double w;
Private double h;
TwoDshape(double w1,double h1){
W=w1;h=h1;}
double getwidth(){ return w};
double getheigth(){ return h};
void setwidth(double w1){w=w1};
void setheigth(double h1){h=h1};
void showdim(){
System.out.println(“Width and Heigth are” +w + “and”+h);
}
}
Class Triangle extends TwoDShape{ Class Shape{
String style; {
Public static void main(String args[]){
Triangle(String s,double w,double h){
Triangle t1=new Triangle(“Filles”,4,4);
Super(w,h); Triangle t2=new Triangle(“Outlined”,8,12);
Style=s; System.out.println(“T1”);
} t1.showstyle(); t1.showdim();
double area(){ System.out.println(“Area”+t1.area());
return getwidth()* getheigth()/2; System.out.println(“T2”);
} t2.showstyle(); t2.showdim();
void showstyle{ System.out.println(“Area”+t2.area());
System.out.println(“Triangle }
}
is”+style);}
}
Using super to call superclass with
default Constructor
Class TwoDShape{
Private double w;
Private double h;
TwoDShape(){ w=h=0;} TwoDShape(double x){w=h=x;}
TwoDshape(double w1,double h1){
W=w1;h=h1;}
double getwidth(){ return w}; double getheigth(){ return h};
void setwidth(double w1){w=w1}; void setheigth(double
h1){h=h1};
void showdim(){
System.out.println(“Width and Heigth are” +w + “and”+h);
}
}
Class Triangle extends TwoDShape{ Class Shape{
String style; {
Triangle(){ super(); style=“none”;} Public static void main(String args[]){
Triangle(double Triangle t1=new Triangle();
x){super(x);style=“filled”} Triangle t2=new Triangle(“Outlined”,8,12);
Triangle(String s,double w,double h){ Triangle t3=new Triangle(4.0);
Super(w,h); t1=t2;
Style=s; System.out.println(“T1”);
} t1.showstyle(); t1.showdim();
double area(){ System.out.println(“Area”+t1.area());
return getwidth()* getheigth()/2; System.out.println(“T2”);
} t2.setwidth(8.0); t2.sewtheigth(12.0);
void showstyle{ System.out.println(“Area”+t2.area());
System.out.println(“Triangle is”+style);} System.out.println(“T3”);
} t3.showstyle(); t3.showdim();
System.out.println(“Area”+t3.area());
} }
Using super to Access Superclass
Member
class A {
int i;
}

class B extends A {
int i;

B(int a,int b){ Class UseSuper {


Super.i=a; public static void main(String args[])
i=b; {
} B subob=new(1,2);
void show(){ subob.show();
System.out.println(“i in Super Class”+super.i); }
System.out.println(“i in subclass”+i);
}
} Output
i in superclass 1
i in subclass 2
Multilevel Hierarchy
 However, you can build hierarchies
that contain as many layers of Multilevel

inheritance as you like.
As mentioned, it is perfectly Hierarchy
acceptable to use a subclass as a
superclass of another. TwoDshape(A)
 For example, given three classes
called A, B, and C, C can be a
subclass of B, which is a subclass of
A. Triangle (B)
 When this type of situation occurs,
each subclass inherits all of the traits
found in all of its superclasses. Colour
 In this case, C inherits all aspects of B Triangle(C)
and A.
Note:- A Subclass can access all the non private members of all its super class
Example-1
class A class C extends B
{ int a; { int c;
}
class B extends A C(int x, int y, int z)
{ int b; {
} a=x; b=y; c=z;
}
void disp()
class MultiLevel {
{ System.out.println("a= "+a+ " b= "+b+" c="+c);
public static void main(String args[]) }
{ }
C ob=new C(2,3,4);
ob.disp();
}
}
Example-2
Class TwoDShape{
Private double w;
Private double h;
TwoDShape(){ w=h=0;} TwoDShape(double x){w=h=x;}
TwoDshape(double w1,double h1){
W=w1;h=h1;}
double getwidth(){ return w}; double getheigth(){ return h};
void setwidth(double w1){w=w1}; void setheigth(double
h1){h=h1};
void showdim(){
System.out.println(“Width and Heigth are” +w + “and”+h);
}
}
Class Triangle extends TwoDShape{ Class ColorTriangle extends Triangle{
Private String style; Private string color;
Triangle(){ super(); style=“none”;} ColorTriangle(String c,String s, double
Triangle(double w,double h){
x){super(x);style=“filled”} super(s,w,h); color=c;
Triangle(String s,double w,double h){ }
Super(w,h); String getcolor(){return color;}
Style=s; void showColor(){
} System.out.println(“Color is “+color);
double area(){ }
return getwidth()* getheigth()/2; }
}
void showstyle{
System.out.println(“Triangle is”+style);}
}
Class Shape{
{
Public static void main(String args[]){
ColorTriangle t1=new ColorTriangle(“Blue”, “Outlined”, 8.0, 12.0);
ColorTriangle t2=new ColorTriangle(“Red”, “Filled”, 2.0, 2.0);
System.out.println(“T1 information”);
t1.showstyle(); t1.showdim(); t1.showColor();
System.out.println(“Area is ”+t1.area());

System.out.println(“T2 information”);
t2.showstyle(); t2.showdim(); t2.showColor();
System.out.println(“Area is ”+t2.area());
}
}
Point to be recalled
class Animal{
String color="white";
}
class Dog extends Animal{
Point to be recalled
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();
}}
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();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}
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();
}}
 A reference of one class type cannot normally refer
to object of another class type.
 In Java strict type enforcement
A reference variable of a super class can be assigned
a reference object of any subclass derived from that
super class
 Or A superclass reference can refer to a subclass
object
Example -1
Class X{ Class X{
Int a; Int a;
X(int i){a=i;} X(int i){a=i;}
Class Y{ Class Y extends X{
Int a; Int a;
Y(int i){a=i;} Y(int i,int j){
Class Incomp{ super(i);
public static void main(String a=i;}
args[]){ Class SupSubRef{
X x=new X(10); public static void main(String args[]){
X x2; X x=new X(10);
Y y=new Y(5); X x2;
x2=x; Y y=new Y(5,6);
X2=y; x2=x;
} X2=y;
}
Example -2
Class TwoDShape{
Private double w;
Private double h;
TwoDshape(TwoDShape ob){
w=ob.w;h=ob.h;}
double getwidth(){ return w};
double getheigth(){ return h};
void setwidth(double w1){w=w1};
void setheigth(double h1){h=h1};
void showdim(){
System.out.println(“Width and Heigth are” +w + “and”+h);
}
}
Class Triangle extends TwoDShape{ Class Shape{
String style; {
Public static void main(String args[]){
Triangle(Triangle ob){
Triangle t1=new Triangle(“Outlined”,8,12);
Super(ob);
style=ob.style; Triangle t2=new Triangle(t1);
} System.out.println(“T1”);
double area(){ t1.showstyle(); t1.showdim();
return getwidth()* getheigth()/2; System.out.println(“Area”+t1.area());
} System.out.println(“T2”);
void showstyle{ t2.showstyle(); t2.showdim();
System.out.println(“Triangle System.out.println(“Area”+t2.area());
}
is”+style);}
}
}
 In a class hierarchy, when a method in a subclass
has the same name and type signature as a method
in its superclass, then the method in the subclass is
said to override the method in the superclass.
 When an overridden method is called from within a
subclass, it will always refer to the version of that
method defined by the subclass.
Example
class A class B extends A
{ {
int i, j; A(int a, int b) int k;
{ B(int a, int b, int c)
i = a; j = b; {
} super(a, b); k = c;
void show() { }
System.out.println("i and j: " + i + " void show() {
" + j); System.out.println("k: " + k); }
} } }

class Override
{
public static void main(String args[])
{
B subOb = new B(1, 2, 3);
subOb.show(); Output:
} } k: 3
void show()
{
super.show(); // this calls A's show()
System.out.println("k: " + k);
}
Dynamic Method Dispatch
 Dynamic Method Dispatch is the mechanism by which a
call to an overridden method is resolved at run time,
rather than compile time.
 Dynamic method dispatch is important because this is
how Java implements run-time polymorphism.
 Java uses this fact to resolve calls to overridden
methods at run time.
 When an overridden method is called through a
superclass reference, Java determines which version of
that method to execute based upon the type of the
object being referred to at the time the call occurs.
Example
class A { class Dispatch {
void callme() { public static void main(String args[]) {
System.out.println("Inside A's callme method"); A a = new A(); // object of type A
} B b = new B(); // object of type B
} C c = new C(); // object of type C
class B extends A { A r; // obtain a reference of type A
void callme() { r = a; // r refers to an A object
System.out.println("Inside B's callme method"); r.callme(); // calls A's version of callme
} r = b; // r refers to a B object
} r.callme(); // calls B's version of callme
class C extends A { r = c; // r refers to a C object
void callme() { r.callme(); // calls C's version of callme
System.out.println("Inside C's callme method"); }
} }
}
Inside A's callme method
Had it been determined by the type of the reference
variable, r, you would see three calls to A’s callme( ) Inside B's callme method
method. Inside C's callme method
Why Overridden Methods?
 Polymorphism is essential to object-oriented
programming for one reason: it allows a general
class to specify methods that will be common to all
of its derivatives, while allowing subclasses to
define the specific implementation of some or all of
those methods.
 Overridden methods are another way that Java
implements the “one interface, multiple methods”
aspect of polymorphism.
 Successfully applying polymorphism is
understanding that the super classes and subclasses
form a hierarchy which moves from lesser to greater
specialization.
 Combining inheritance with overridden methods, a
superclass can define the general form of the
methods that will be used by all of its subclasses.
 Dynamic, run-time polymorphism is one of the most
powerful mechanisms that object oriented design
brings to bear on code reuse and robustness.
Using Abstract Classes
 Situations in which you will want to define a superclass that
declares the structure of a given abstraction without
providing a complete implementation of every method.
 Sometimes you will want to create a superclass that only
defines a generalized form that will be shared by all of its
subclasses, leaving it to each subclass to fill in the details
 A method which does not contain any definition in the
superclass is termed as abstract method.
 Such a method declaration should be preceded by the
keyword abstract.
 Methods are sometimes referred to as subclasser
responsibility because they have no implementation
specified in the superclass.
abstract type name(parameter-list);
 The Abstract modifier can be used for normal
methods
 It cannot be applied for static or to constructors
 A class that contains one or more abstract method
must be declared as abstract by preceding class
declaration with abstract modifier.
 Abstract classes can not be instantiated, that is one
cannot create an object of abstract class. Whereas,
a reference can be created for an abstract class.
Example-1
abstract class A class B extends A
{ {
abstract void callme(); void callme()
void callmetoo() {
{ System.out.println("B's implementation of
System.out.println("This is a concrete callme.");
method."); }
} }
}
class AbstractDemo {
public static void main(String args[])
{
B b = new B();
b.callme();
b.callmetoo();
}
}
Example -2
class Triangle extends Shape
abstract class Shape
{
{
int b, h;
final double PI= 3.1416;
Triangle(int x, int y) //constructor
abstract double area();
{
}
b=x; h=y;
}

double area() //method overriding


{
System.out.print("\nArea of Triangle is:");
return 0.5*b*h;
}
}
Example -2
class Circle extends Shape class Rectangle extends Shape
{ {
int r; int a, b;
Circle(int rad) //constructor Rectangle(int x, int y)
{ //constructor
r=rad; {
} a=x; b=y;
double area() //overriding }
{ double area() //overriding
System.out.print("\nArea of Circle {
is:"); System.out.print("\nArea of Rectangle
return PI*r*r; is:"); return a*b;
} }
} }
Example -2
class AbstractDemo
{
public static void main(String args[])
{
Shape r[]={new Triangle(3,4), new Rectangle(5,6) ,new Circle(2)};
for(int i=0;i<3;i++)
System.out.println(r[i].area());
}
}

Output:
Area of Triangle is:6.0
Area of Rectangle is:30.0
Area of Circle is:12.5664
Recall Points
Using Final

 The keyword final can be used in three


situations in Java:
 To create the equivalent of a named constant.
 To prevent method overriding
 To prevent Inheritance
To create the equivalent of a named
constant
 A variable can be declared as final.
Doing so prevents its contents from final int FILE_NEW = 1;
being modified. This means that you final int FILE_OPEN = 2;
must initialize a final variable when final int FILE_SAVE = 3;
it is declared. final int FILE_SAVEAS = 4;
 Variables declared as final do not final int FILE_QUIT = 5;
occupy memory on a per-instance
basis.
 Thus, a final variable is essentially a
constant.
 The value cannot be changed
throughout the lifetime of program
To prevent method overriding

 Sometimes, we do not class A


want a superclass method {
to be overridden in the final void meth()
{
subclass. System.out.println("This is a final
 Instead, the same method.");
superclass method }
definition has to be used }
class B extends A
by every subclass. {
 In such situation, we can void meth()// ERROR! Can't
prefix a method with the override.
{
keyword final System.out.println("Illegal!");
}
}
To prevent Inheritance

 The subclass is treated as a


specialized class and final class A
superclass is most generalized {
class. // ...
 During multi-level inheritance, }
the bottom most class will be class B extends A// ERROR! Can't
with all the features of real- subclass A
time and hence it should not be {
inherited further. // ...
 In such situations, we can }
prevent a particular class from
inheriting further, using the
keyword final.
The Object Class
 There is one special class, Object, defined by Java.
All other classes are subclasses of Object.
 That is, Object is a superclass of all other classes.
 The reference variable of type Object can refer to
an object of any other class.
 Since arrays are implemented as classes, a variable
of type Object can also refer to any array.
The Object Class
Method Purpose
Object clone( ) Creates a new object that is the same as the
object being cloned.
boolean equals(Object object) Determines whether one object is equal to
another.
void finalize( ) Called before an unused object is recycled.
Class getClass( ) Obtains the class of an object at run time.
int hashCode( ) Returns the hash code associated with the
invoking object.
void notify( ) Resumes execution of a thread waiting on the
invoking object.
void notifyAll( ) Resumes execution of all threads waiting on the
invoking object.
String toString( ) Returns a string that describes the object.
void wait( ) void wait(long milliseconds) Waits on another thread of execution.
void wait(long milliseconds, int
nanoseconds)
The Object Class
 The methods getClass( ), notify( ), notifyAll( ), and
wait( ) are declared as final.
 The equals( ) method compares the contents of two
objects. It returns true if the objects are equivalent, and
false otherwise.
 The precise definition of equality can vary, depending
on the type of objects being compared.
 The toString( ) method returns a string that contains a
description of the object on which it is called. Also, this
method is automatically called when an object is output
using println( ).

You might also like