Abstract Class
Abstract Class
There are some related classes that need to share some lines of
code, so these lines of codes can be put within abstract class
class Main {
public static void main(String args[]) {
DerivedClass d = new DerivedClass();
Output:
}
} MyBaseClass Constructor called
DerivedClass Constructor called
Shape(String name) {
this.objectName = name;
}
// 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); }
}
System.out.println(" ");
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
2. private
3. protected
4. public
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…
Is a Cat an Object?
class Animal {
int health = 100;
}
class Mammal extends Animal { }
class Cat extends Mammal { }
class Dog extends Mammal { }
Output?
Output?
E.g.,
is equal to
stroke(c);
stroke(d); //automatic upcast to an Animal
Animal aa=c;
stroke(aa);
10/23/2024 Inheritance Page 29