Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract classes, why can't we declare private val and var class member?

Tags:

scala

abstract class Table {
  private val records: Int
}

Is it because we have to create an instance of an abstract class before we can access its private member?

like image 308
mythicalprogrammer Avatar asked Sep 11 '11 03:09

mythicalprogrammer


People also ask

Can we declare private variable in abstract class?

Abstract classes can have private methods. Interfaces can't. Abstract classes can have instance variables (these are inherited by child classes).

Can we make abstract method as private?

But, incase of an abstract method, you cannot use it from the same class, you need to override it from subclass and use. Therefore, the abstract method cannot be private.

Why we can create constructor in abstract class but we Cannot initialize it why Java introduced this?

The main purpose of the constructor is to initialize the newly created object. In abstract class, we have an instance variable, abstract methods, and non-abstract methods. We need to initialize the non-abstract methods and instance variables, therefore abstract classes have a constructor.

Can abstract class have private variables in C#?

An abstract method cannot be private as in the following, abstract class Demo() { private abstract void Call();


2 Answers

To extend a bit on @Owen's answer: you can declare private members.

abstract class Table {
  private val records: Int = 0
}

But you can't declare abstract private members. Why? Because any concrete class which extends an abstract class must override any abstract members, and it can't override a private member. So you couldn't have any concrete classes which extend Table at all.

like image 181
Alexey Romanov Avatar answered Nov 08 '22 22:11

Alexey Romanov


I would imagine this is because there is no way to make them concrete:

class Foo extends Table {
    override val records = 3
}

would fail, because records is private to Table.

It would make Table kind of useless. I can't see that it would hurt anything, just it almost certainly indicates a mistake by the programmer.

like image 31
Owen Avatar answered Nov 08 '22 20:11

Owen