抽象类可以有构造函数吗?
如果可以,如何使用它,用于什么目的?
抽象类可以有构造函数吗?
如果可以,如何使用它,用于什么目的?
当前回答
由于抽象类可以拥有所有访问修饰符的变量,因此必须将它们初始化为默认值,因此构造函数是必要的。 在实例化子类时,将调用抽象类的构造函数并初始化变量。
相反,接口只包含常量变量意味着它们已经初始化。所以接口不需要构造函数。
其他回答
是的。当创建继承类的实例时,调用抽象类的构造函数。例如,下面是一个有效的Java程序。
// An abstract class with constructor
abstract class Base {
Base() { System.out.println("Base Constructor Called"); }
abstract void fun();
}
class Derived extends Base {
Derived() { System.out.println("Derived Constructor Called"); }
void fun() { System.out.println("Derived fun() called"); }
}
class Main {
public static void main(String args[]) {
Derived d = new Derived();
}
}
这是上面代码的输出,
基本构造函数Called 派生构造函数调用
引用: 在这里输入链接描述
是的,抽象类可以有构造函数!
下面是一个在抽象类中使用构造函数的例子:
abstract class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
// area is now an abstract method
abstract double area();
}
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;
}
}
class AbstractAreas {
public static void main(String args[]) {
// Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref; // this is OK, no object is created
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
}
}
我想你已经得到答案了。
虽然有很多好的答案,但我还是想提出我的意见。
构造函数不构建对象。它用于初始化对象。
是的,抽象类总是有一个构造函数。如果您没有定义自己的构造函数,编译器将为Abstract类提供一个默认构造函数。 以上对所有类都适用——嵌套的、抽象的、匿名的等等。
抽象类(与接口不同)可以具有需要初始化的非最终非静态字段。您可以在抽象类中编写自己的构造函数来实现这一点。但是,在这种情况下,不会有任何默认构造函数。
public abstract class Abs{
int i;
int j;
public Abs(int i,int j){
this.i = i;
this.j = j;
System.out.println(i+" "+j);
}
}
在扩展上述抽象类时要小心,必须从每个构造函数显式地调用super。任何构造函数的第一行都调用super()。如果您没有显式地调用super(), Java将为您完成。 以下代码将无法编译:
public class Imp extends Abs{
public Imp(int i, int j,int k, int l){
System.out.println("2 arg");
}
}
你必须像下面的例子那样使用它:
public class Imp extends Abs{
public Imp(int i, int j,int k, int l){
super(i,j);
System.out.println("2 arg");
}
}
考虑一下:
abstract class Product {
int value;
public Product( int val ) {
value= val;
}
abstract public int multiply();
}
class TimesTwo extends Product {
public int mutiply() {
return value * 2;
}
}
超类是抽象的,并且有一个构造函数。
是的,抽象类可以有构造函数。可以在抽象类中重载任意数量的构造函数。这些承包商可以用来初始化扩展抽象类的对象的初始状态。正如我们所知,我们不能创建抽象类的对象,因为对象是由“new”关键字创建的,而不是由构造函数创建的……它们只用于初始化子类对象的状态。