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

Classes Inheritance Interface Abstract.pptx

The document provides a comprehensive overview of classes and objects in Java, emphasizing their role as fundamental components of the language. It covers class definitions, object creation, methods, constructors, and inheritance, along with practical examples to illustrate these concepts. Additionally, it discusses method overloading and the use of 'this' and 'super' in constructors, showcasing how these features enhance object-oriented programming in Java.

Uploaded by

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

Classes Inheritance Interface Abstract.pptx

The document provides a comprehensive overview of classes and objects in Java, emphasizing their role as fundamental components of the language. It covers class definitions, object creation, methods, constructors, and inheritance, along with practical examples to illustrate these concepts. Additionally, it discusses method overloading and the use of 'this' and 'super' in constructors, showcasing how these features enhance object-oriented programming in Java.

Uploaded by

Anvi Suri
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

Classes and Objects in Java

Basics of Classes in Java


By. Ms Gargi Mukherjee

1
Contents

• Introduction to classes and objects in Java.


• Understand how some of the OO concepts learnt so
far are supported in Java.
• Understand important features in Java classes.

2
Introduction
• Java is a true Object Oriented language and therefore
the underlying structure of all Java programs is
classes.
• Anything we wish to represent in Java must be
encapsulated in a class that defines the “state” and
“behavior” of the basic program components known
as objects.
• Classes create objects and objects use methods to
communicate between them.

3
Classes
• A class is a user defined abstract datatype.
class Box { mybox
double width; Widwidth=
10
,length=15,
double length;
Depth=12
double depth;
} to create the object syntax
Box mybox=new Box( );
4
Program to demonstrate working of a
class

5
class Box {
double width; //declared variables
double length;
double depth;
}
// This class declares an object of type Box.
class BoxDemo {
public static void main(String args[ ]) {
Box mybox = new Box(); //an object mybox of the class box is created,new is
the keyword thru which it is created.
Box mybox1=new Box();
double vol;
// assign values to mybox's instance variables
mybox.width = 10;
mybox.length = 20;
mybox.depth = 15;
mybox1.width = 20;
mybox1.length =30;
mybox1.depth = 45;

// compute volume of box 6

vol = mybox.width * mybox.length * mybox.depth;//(10*20*15)


Adding Methods(functions)
• A class with only data fields has no life.
Objects created by such a class cannot
respond to any messages.
• Methods are declared inside the body of the
class but immediately after the declaration of
data fields.
• The general form of a method declaration is:
returntype MethodName (parameter-list)
{
Method-body;
7
}
Adding Methods to Class Circle
class Box {
double width;
double length;
double depth;

// display volume of a box


void volume() {
System.out.print("Volume is ");
System.out.println(width * length * depth);
}
} Method
Body
8
class BoxDemo3 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box(); W=10,l=20,
3,6,9
d=15
// assign values to mybox1's instance variables
mybox1.width = 10; myobj1 myobj2
mybox1.length = 20;
mybox1.depth = 15;

/* assign different values to mybox2's


instance variables */
mybox2.width = 3;
mybox2.length = 6;
mybox2.depth = 9;
// display volume of first box
mybox1.volume(); //function is going to get called
// display volume of second box
mybox2.volume();
}
9
}
Now, volume() returns the volume of a
class Box { box.
double width;
double length;
double depth;

// compute and return volume


double volume() {
return width * length * depth;
}
}
10
class BoxDemo4 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.length = 20;
mybox1.depth = 15;
/* assign different values to mybox2's
instance variables */
mybox2.width = 3;
mybox2.length = 6;
mybox2.depth = 9;

// get volume of first box


vol= mybox1.volume();
System.out.println("Volume is " + vol);

// get volume of second box


vol = mybox2.volume();
System.out.println("Volume is " + vol); 11
}
}
class Box {
double width;
Parametrised method demo
double length;
double depth;

// compute and return volume


double volume() {
return width * length * depth;
}
// sets dimensions of box
void setDim(double w, double h, double d) {
width = w;
length = h;
depth = d;
} 12

}
class BoxDemo5 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;

// initialize each box


mybox1.setDim(10, 20, 10);
mybox2.setDim(3, 3, 3);

// get volume of first box


vol = mybox1.volume();
System.out.println("Volume is " + vol);

// get volume of second box


vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
O/P 13
Volume is: 2000
Volume is: 27
Adding constructors to class
• Constructor has same name as that of its class.
• Constructors do not have return type not even void
• They are used to initialize object of the class, etc.
class Box {
double width;
double length;
double depth;

// efault constructor for Box.


Box() {
System.out.println("Constructing Box");
width = 10;
length = 10;
depth = 10;
}
Box(double w, double h, double d) {
width = w;
length = h;
depth = d;
}

// compute and return volume


double volume() {
return width * length * depth;
}
15
}
class BoxDemo7 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 10);
Box mybox2 = new Box();

double vol;

// get volume of first box


vol = mybox1.volume();
System.out.println("Volume is " + vol);

// get volume of second box


vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
O/P 16

Volume is: 2000


Volume is: 1000
this

// A redundant use of this.


Box(double w, double h, double d) {
this.width = w;
this.length = h;
this.depth = d;
}

17
Use this to resolve naming collisions.

Box(double width, double length, double depth)


{
this.width = width;

this.length = length;

this.depth = depth;
}

18
class Stack {
int stck[] = new int[10];
int tos;

// Initialize top-of-stack
Stack() {
tos = -1;
}

// Push an item onto the stack


void push(int item) {
if(tos==9)
System.out.println("Stack is full.");
else
stck[++tos] = item;
}

// Pop an item from the stack


int pop() {
if(tos < 0) {
System.out.println("Stack underflow.");
return 0; 19
}
else
class TestStack {
public static void main(String args[]) {
Stack mystack1 = new Stack();
Stack mystack2 = new Stack();

// push some numbers onto the stack


for(int i=0; i<10; i++)
mystack1.push(i);
for(int i=10; i<20; i++)
mystack2.push(i);

// pop those numbers off the stack


System.out.println("Stack in mystack1:");
for(int i=0; i<10; i++)
System.out.println(mystack1.pop()); System.out.println("Stack in
mystack2:");
for(int i=0; i<10; i++)
System.out.println(mystack2.pop());
}
}

20
Summary

• Classes, objects, and methods are the basic


components used in Java programming.
• We have discussed:
• How to define a class
• How to create objects
• How to add data fields and methods to classes
• How to access data fields and methods to classes
21
Write a program to create a class Student with following
members:
Data members:
Sname
Class
Age
Methods:
Constructors
readVal()
showVal()
Create a separate class with main function defined in it .
Program should create 2 objects for the class Student.

22
Program to add two distances

23
class Distance
{
int feet, inches;
Distance()
{
feet=inches=0;
}
Distance(int x)
{
feet=inches=x;
}
Distance(int x1, int x2)
{
feet=x1;
inches=x2;
}

void addDistance(Distance di, Distance dj)


{
24
feet=di.feet+dj.feet;
inches=di.inches+dj.inches;
if(inches>=12)
class DistanceDemo
{

public static void main(String args[])


{

Distance d1 =new Distance(5,12);


Distance d2 =new Distance(5,1);
Distance d3 =new Distance();

System.out.println("First Object Details are: ");


d1.show();
System.out.println("Second Object Details are: ");
d2.show();
d3.addDistance(d1,d2);
System.out.println("Third Object Details are: ");
d3.show(); 25
}
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a) {
System.out.println("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
}

26
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;

// call all versions of test()


ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}

27
Inheritance

28
class A {
int i, j;

void showij() {
System.out.println("i and j: " + i + " " + j);
}
}

class B extends A {
int k;

void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
} 29

}
class SimpleInheritance {
public static void main(String args[]) {
A a = new A();
B b = new B();
a.i = 10;
a.j = 20;
System.out.println("Contents of a: ");
a.showij();
System.out.println();
b.i = 7;
b.j = 8;
b.k = 9;
System.out.println("Contents of b: ");
b.showij();
b.showk();
System.out.println();

System.out.println("Sum of i, j and k in b:");


b.sum();
}
}
30
class Box {
double width;
double length;
double depth;

// construct clone of an object


Box(Box ob) { // pass object to constructor
width = ob.width;
length = ob.length;
depth = ob.depth;
}

// constructor used when all dimensions specified


Box(double w, double h, double d) {
width = w;
length = h;
depth = d;
}

// constructor used when no dimensions specified


31

Box() {
class BoxWeight extends Box
{

double weight;

// constructor for BoxWeight with 4 arguments

BoxWeight(double w, double l, double d, double m)


{
width = w;
length = l;
depth = d;
weight = m;
}
}
32
class DemoBoxWeight {
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);
}
}

33
Use of super

34
class Box {
private double width;
private double length;
private double depth;

// construct clone of an object


Box(Box ob) { // pass object to constructor
width = ob.width;
length = ob.length;
depth = ob.depth;
}

// constructor used when all dimensions specified


Box(double w, double l, double d) {
width = w;
length = l;
depth = d;
}

// constructor used when no dimensions specified


Box() {
35
width = -1; // use -1 to indicate
length = -1; // an uninitialized
depth = -1; // box
// BoxWeight now fully implements all constructors.
class BoxWeight extends Box
{
double weight;

// construct clone of an object


BoxWeight(BoxWeight ob)
{ // pass object to constructor
super(ob);
weight = ob.weight;
}

// constructor when all parameters are specified


BoxWeight(double w, double l, double d, double m) {
super(w, l, d); // call superclass 3 argument constructor
weight = m;
}

// default constructor
BoxWeight() {
super(); 36
weight = -1;
}
class DemoSuper {
public static void main(String args[]) {
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
BoxWeight mybox3 = new BoxWeight(); // default
BoxWeight mycube = new BoxWeight(3, 2);
BoxWeight myclone = new BoxWeight(mybox1);
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);
System.out.println();

vol = mybox3.volume();
System.out.println("Volume of mybox3 is " + vol);
37
System.out.println("Weight of mybox3 is " + mybox3.weight);
System.out.println();
Order of constructor calling in Inheritance

38
// 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 { 39

public static void main(String args[]) {


C c = new C();
O/P:
Inside A’s Constructor
Inside B’s Constructor
Inside C’s Constructor

40
Overridding Methods

41
// Method overriding.
class A {
int i, j;

A(int a, int b) {
i = a;
j = b;
}

// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}
}

class B extends A {
int k;

B(int a, int b, int c) {


super(a, b);
k = c; 42
}
class B extends A {
int k;
Another Style
B(int a, int b, int c) {
super(a, b);
k = c;
}

void show() {
super.show(); // this calls A's show()
System.out.println("k: " + k);
}
}
43
Use of “abstract”

44
Abstract Classes
• Class containing one or more function as abstract is
known as abstract class and therefore its declaration
should be preceded with the keyword abstract.
• An Abstract class is a conceptual class.
• An Abstract class cannot be instantiated – objects cannot
be created.
• A class declared abstract, even with no abstract methods
can not be instantiated.
• A subclass of an abstract class can be instantiated if it
overrides all abstract methods by implementation them.
• A subclass that does not implement all of the superclass
abstract methods is itself abstract; and it cannot be
45

instantiated.
Abstract Class Syntax
abstract class ClassName
{
...

abstract Type MethodName1();


Type Method2()
{
// method body
}
}
• When a class contains one or more abstract methods, it should be declared as abstract class.
• The abstract methods of an abstract class must be defined in its subclass.
• We cannot declare abstract constructors or abstract static methods.
46
For eg:
abstract class Figure {
double dim1;
double dim2;

Figure(double a, double b) {
dim1 = a;
dim2 = b;
}

// area is now an an abstract method


abstract double area();
}

47
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}

// override area for rectangle


double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}

class Triangle extends Figure {


Triangle(double a, double b) {
super(a, b);
}

// override area for right triangle


double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2; 48
}
}
class AbstractAreas {
public static void main(String args[]) {
// Figure f = new Figure(10, 10); is illegal now
as it cannot be instantiated
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);

System.out.println("Area is " + r.area());


System.out.println("Area is " + t.area());
}
}

49
Final Members: A way for
Preventing Overriding of Members
in Subclasses
• All methods and variables can be overridden by
default in subclasses.
• This can be prevented by declaring them as final
using the keyword “final” as a modifier. For
example:
• final int marks = 100;
• final void display();
• This ensures that functionality defined in this
method cannot be altered any. Similarly, the value
of a final variable cannot be altered.
50
FINAL METHOD
class A {
final void meth() {
System.out.println("This is a final method.");
}
}

class B extends A {
void meth() { // ERROR! Can't override.
System.out.println("Illegal!");
}
}
FINAL CLASS
final class A {
// ...
}

// The following class is illegal.


class B extends A { // ERROR! Can't subclass A
51
// ...
}
Interfaces

Design Abstraction and a way for achieving Multiple


Inheritance

52
Interfaces

• Interface is a conceptual entity similar to a


Abstract class.
• Can contain only constants (final fields) and
abstract method. (no implementation) - Different
from Abstract classes.
• When number of classes share a common
interface each class should implement the
interface.
53
Features
• An interface of ana kind
is basically Interface
of class—it contains
methods and final fields.
• Therefore, it is the responsibility of the class that
implements an interface to supply the code for
methods.
• A class can implement any number of interfaces, but
cannot extend more than one class at a time.
• Therefore, interfaces are considered as an informal way
of realising multiple inheritance in Java.
54
Interface - Example
<<Interface>>
Speaker
speak()

Politician Priest Lecturer


speak() speak() speak()
55
Interfaces Definition

interface
• Syntax InterfaceName
(appears like abstract{class):
// Constant/Final Variable Declaration
// Methods Declaration – only method body
}

• Example:
interface Speaker {
public void speak( );
}
56
Implementing Interfaces

• Interfaces are used like super-classes who properties


are inherited by classes. This is achieved by creating a
class that implements the given interface as follows:

class ClassName implements InterfaceName [, InterfaceName2, …]


{
// Body of Class
}

57
class Politician implements Speaker {
Implementing Interfaces Example
public void speak(){
System.out.println(“Talk politics”);
}
}

class Priest implements Speaker {


public void speak(){
System.out.println(“Religious Talks”);
}
}

class Lecturer implements Speaker {


public void speak(){
System.out.println(“Talks Object Oriented Design and Programming!”);
} 58

}
Extending Interfaces

• Like classes, interfaces can also be extended.


The new sub-interface will inherit all the
members of the superinterface in the manner
similar to classes. This is achieved by using
interface
the keywordInterfaceName2 extends InterfaceName1
extends as follows:
{
// Body of InterfaceName2
}
59
Inheritance and Interface
Implementation
class ClassName
• A general formextends SuperClass
of interface implements InterfaceName [,
implementation:
InterfaceName2, …]
{
// Body of Class
}

• This shows a class can extended another class while


implementing one or more interfaces. It appears like a multiple
inheritance (if we consider interfaces as special kind of classes
with certain restrictions or special features).
60
/* An example Java Program to demontrate the working of an Interface*/

interface Shape
{
float PI=3.14f;
float computeArea();
}

class Circle implements Shape


{
float radius;
Circle (float r)
{
radius=r;
}

public float computeArea()


{
return PI*radius*radius;
}
61

}
Java 8 Default Methods
Interfaces in Java always contained method declaration not
their definitions (method body). There was no way of
defining method body / definition in interfaces. This is
because historically Java didn’t allow multiple inheritance of
classes. It allowed multiple inheritance of interfaces as
interface were nothing but method declaration. This solves
the problem of ambiguity in multiple inheritance. Since Java
8 has a new feature called Default Methods. It is now
possible to add method bodies into interfaces!

62
public interface Math
{
int add(int a, int b);
default int multiply(int a, int b)
{
return a * b;
}
}
In above Math interface we added a method
multiply with actual method body.
63
Why we need Default Methods?
or
Why would one want to add methods into
Interfaces?
We’ll it is because interfaces are too tightly coupled
with their implementation classes. i.e. it is not
possible to add a method in interface without
breaking the implementer class. Once you add a
method in interface, all its implemented classes must
declare method body of this new method.

64
What about Multiple Inheritance?
Adding method definitions in interfaces can add ambiguity in multiple inheritance. isn’t it?
Well, it does. However Java 8 handle this issue at Compile type. Consider below example:

interface Person
{
default void sayHello()
{
System.out.println("Hello");
}
}
interface Male
{
default void sayHello()
{
System.out.println("Hi");
}
}
class Sam implements Person, Male
{

65

}
In this example we have same defender method sayHello in
both interfaces Person and Male. Class Sam implements these
interfaces. So which version of sayHello will be inherited?
We’ll if you try to compile this code in Java 8, it will give
following error.

class Sam inherits unrelated defaults for sayHello() from


types Person and Male class Sam implements Person,
Male { ^ 1 error

So that solves multiple inheritance problem. You cannot


implement multiple interfaces having same signature of Java 8
default methods (without overriding explicitly in child class).
66
We can solve the above problem by overriding sayHello method
in class Sam.
interface Person
{
default void sayHello()
{
System.out.println("Hello");
}
}
interface Male
{
default void sayHello()
{
System.out.println("Hi");
}
}
class Sam implements Person, Male
{
void sayHello() //override the sayHello to resolve ambiguity
{ 67
}
}
It is also possible to explicitly call method from child
class to parent interface. Consider in above example
you want to call sayHello method from Male interface
when Sam.sayHello is called. You can use super keyword to
explicitly call the appropriate method.
class Sam implements Person, Male
{
//override the sayHello to resolve ambiguity
void sayHello()
{
Male.super.sayHello();
}
} 68

You might also like