0% found this document useful (0 votes)
15 views29 pages

Abstract Class

.

Uploaded by

23020661
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)
15 views29 pages

Abstract Class

.

Uploaded by

23020661
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/ 29

Inheritance (cont.

Vũ Thị Hồng Nhạn

([email protected])

Dept. of Software Engineering, UET

Vietnam National Univ., Hanoi


Abstract classes in Java
Abstract class & method
 Goal: hiding the internal implementation of the features and
only showing the functionality to the users

 There are some related classes that need to share some lines of
code, so these lines of codes can be put within abstract class

 this abstract class should be extended by all these related classes

 can include abstract method

 But, abstract method must be overridden in the inherited classes

10/23/2024 Inheritance Page 3


Cannot create an object of an abstract class
abstract class Shape {
protected int x, y;
Shape(int x1, int y1) {
x = x1; y = y1;
}
}
class Circle extends Shape
{ ...
}

Shape s = new Shape(10, 10) // compile error


Shape s = new Circle();

10/23/2024 Inheritance Page 4


Constructor of abstract class is called

when creating an object of inherited class


abstract class MyBase {
MyBase() { System.out.println(“MyBaseClass Constructor called"); }
abstract void fun();
}
class DerivedClass extends MyBase {
DerivedClass() { System.out.println("DerivedClass Constructor called"); }
void fun() { System.out.println("DerivedClass fun() called"); }
}

class Main {
public static void main(String args[]) {
DerivedClass d = new DerivedClass();
Output:
}
} MyBaseClass Constructor called
DerivedClass Constructor called

10/23/2024 Inheritance Page 5


Example
import java.io.*;
abstract class Shape {

String objectName = " ";

Shape(String name) {
this.objectName = name;
}

public void moveTo(int x, int y) {


System.out.println(this.objectName + " " + "has been moved to"
+ " x = " + x + " and y = " + y);
}

// abstract methods which will be


// implemented by its subclass(es)
abstract public double area();
abstract public void draw();
}

10/23/2024 Inheritance Page 6


Example…
class Rectangle extends Shape{

int length, width;

// constructor
Rectangle(int length, int width, String name) {
super(name);
this.length = length;
this.width = width;
}

@Override
public void draw() {
System.out.println("Rectangle has been drawn ");
}

@Override
public double area() {
return (double)(length*width);
}
}
10/23/2024 Inheritance Page 7
Example…
class Circle extends Shape {
double pi = 3.14; int radius;

//constructor
Circle(int radius, String name) {
super(name);
this.radius = radius;
}
@Override
public void draw() {
System.out.println("Circle has been drawn "); }

@Override
public double area() {
return (double)((pi*radius*radius)/2); }
}

10/23/2024 Inheritance Page 8


Example…
class MAIN{
public static void main (String[] args) {

// creating the Object of Rectangle class


// and using shape class reference.
Shape rect = new Rectangle(2,3, "Rectangle");
System.out.println("Area of rectangle: " + rect.area());
rect.moveTo(1,2);

System.out.println(" ");

// creating the Objects of circle class


Shape circle = new Circle(2, "Cicle");
System.out.println("Area of circle: " + circle.area());
circle.moveTo(2,4);
}
}

10/23/2024 Inheritance Page 9


Access modifiers in Java
Example
Person Employee e = new Employee();
-name ...
-birthday
+setName()
e.setName("John");
+getName() e.setSalary(3.0);
+setBirthday()
System.out.print(e.getName());
extend
Employee
-salary
+setSalary()
+getDetail()

2024-10-23 Kế thừa 11
Accessing members of the base class from subclass

Person
-name
-birthday
+setName()
class Employee extends Person { +getName()
... +setBirthday()
public String getDetail() { extend
String s;
Employee
s = name + "," + birthday; -salary
//s = getName() + "," + getBirthday(); +setSalary()
s += "," + salary; +getDetail()
return s;
}
}
10/23/2024 Kế thừa Page 12
Access modifiers
 Help restrict the scope of a class, constructor, variable, method,
or data member

 Four types of access modifiers in java

1. default: no keyword required

2. private

3. protected

4. public

10/23/2024 Inheritance Page 13


Example

in the same package


public class Person {
Date birthday; default
String name;
...
}

public class Employee extends Person {


...
public String getDetail() {
String s;
s = name + "," + birthday;
s += "," + salary;
return s;
}
}

10/23/2024 Kế thừa Page 14


The protected access modifier
 The method or data members declared as protected are
accessible within
 same package
 or sub classes in different packages

10/23/2024 Inheritance Page 15


Example: in same package

public class Person {


protected Date birthday;
protected String name;
...
}

public class Employee extends Person {


...
public String getDetail() {
String s;
s = name + "," + birthday;
s += "," + salary;
return s;
}
}
10/23/2024 Kế thừa Page 16
Example

in different packages
package abc;
public class Person {
protected Date birthday;
protected String name;
...
}

import abc.Person;
public class Employee extends Person {
...
public String getDetail() {
String s;
s = name + "," + birthday;
s += "," + salary;
return s;
}
}
10/23/2024 Kế thừa Page 17
4 types of access modifiers…

10/23/2024 Kế thừa Page 18


Casting objects
Upcasting vs. Downcasting
 Java allows an object of a subclass to
be treated as an object of any super
class

 This is called upcasting

 Upcasting is done automatically

 Downcasting is also allowed but it


must be done manually

 But upcasting & downcasting are


not like casting primitive data types

10/23/2024 Inheritance Page 20


Upcasting
 Cat & Dog are both Mammals, which parent
extends from Animal, which
automatically extends from Object

 in Java, everything is an Object except children


primitives

 Is a Cat an Object?

 Yes, because by inheritance Cat gets all


the properties its ancestors have

 Cat is also an Animal and a Mammal too


Animal hierarchy

10/23/2024 Inheritance Page 21


Upcasting: example

class Animal {
int health = 100;
}
class Mammal extends Animal { }
class Cat extends Mammal { }
class Dog extends Mammal { }

public class Test {


public static void main(String[] args) {
Cat c = new Cat();
System.out.println(c.health);
Dog d = new Dog();
System.out.println(d.health);
}
}

Output?

10/23/2024 Inheritance Page 22


Upcasting: example

Cat c = new Cat();


System.out.println(c);
Mammal m = c; // upcasting
System.out.println(m);

Output?

 Cat is exactly the same after casting . Cat didn’t change to a


Mammal, it is just being labeled Mamal now

10/23/2024 Inheritance Page 23


Upcasting…

 Upcasting can be done automatically

 E.g.,

Mammal m= (Mammal) new Cat();

is equal to

Mammal m = new Cat();

10/23/2024 Inheritance Page 24


Downcasting
 Downcasting must always be done manually

 Cat c1 = new Cat();


 Animal a= c1; //upcasting to an Animal automatically
 Cat c2= (Cat) a; //manually downcasting back to a Cat

10/23/2024 Inheritance Page 25


instanceof
 is used to test if an object is an instance of some class
Cat c1 = new Cat();
Animal a = c1; //upcasting to Animal
if(a instanceof Cat){ // testing if the Animal is a Cat
System.out.println("It's a Cat! safely downcast it to a Cat");
Cat c2 = (Cat)a;
}
 What about?
Dog d=new Dog(); Animal a=d; Cat c2=(Cat)a;
 Don’t confuse variables with instances!
 Cat from a Animal variable can be cast to a Cat
 but, Animal from a Animal variable cannot be cast to a Cat

10/23/2024 Inheritance Page 26


Casting…
 Casting cannot always be done in both ways
 if you’re creating a Mammal (by calling new Mammal())
 but it cannot be downcasted to Dog or Cat
 E.g.
Mammal m = new Mammal();
Cat c = (Cat)m;
 This code passes compiling, but throw java.lang.ClassCastException
exception while running because Mammal is not a Cat but we’re trying to cast to
a Cast

10/23/2024 Inheritance Page 27


Casting…
 If you upcast an object, it will lose all the
properties which were inherited from its
current position
 Data will not be lost, you just can’t use it
till you downcast the object to the right
level
 Why?
 If you have a group of animals, then you
cannot be sure which one can meow() and
which one can bark()
 That’s why you cannot make animal do
things!

10/23/2024 Inheritance Page 28


Upcasting during method calling
 We can make general methods, which can take different classes as an
argument

public static void stroke(Animal a){


System.out.println(“you stroke the ” + a);
}

Cat c= new Cat();


Dog d= new Dog();

stroke(c);
stroke(d); //automatic upcast to an Animal

Animal aa=c;
stroke(aa);
10/23/2024 Inheritance Page 29

You might also like