한 클래스가 두 클래스를 확장 할 수 있습니까?
내 클래스는 동시에 두 클래스를 확장해야합니다.
public class Preferences extends AbstractBillingActivity {
public class Preferences extends PreferenceActivity {
어떻게하나요?
업데이트 . 이것이 가능하지 않기 때문에 AbstractBillingActivity 를 Preferences와 함께 어떻게 사용해야 합니까?
Upd2 . 인터페이스를 사용하는 경우 다음을 만들어야합니다.
BillingInterface
public interface BillingInterface extends PreferenceActivity, AbstractBillingActivity { }
PreferenceActivity
public interface PreferenceActivity { }
AbstractBillingActivity
public interface AbstractBillingActivity { void onCreate(Bundle savedInstanceState); }
그리고
public class Preferences implements BillingInterface {
Java는 다중 상속을 지원하지 않습니다.
생각할 수있는 몇 가지 해결 방법이 있습니다.
첫 번째는 집계입니다.이 두 활동을 필드로 사용하는 클래스를 만듭니다.
두 번째는 인터페이스를 사용하는 것입니다.
세 번째는 당신의 디자인을 재고하는 것입니다 : 그것은에 대한 이해가 않습니다 Preferences
클래스 것은 모두 할 수 PreferenceActivity
및 을 AbstractBillingActivity
?
Java는 다중 상속을 지원하지 않습니다. 여러 인터페이스를 구현할 수 있지만 여러 클래스를 확장 할 수는 없습니다.
또 다른 해결책은 두 번째 클래스를 확장하는 개인 내부 클래스를 만드는 것입니다. 예를 들어 확장하는 클래스 JMenuItem
및 AbstractAction
:
public class MyClass extends JMenuItem {
private class MyAction extends AbstractAction {
// This class can access everything from its parent...
}
}
Java 1.8 (Groovy 및 Scala 포함)에는 사전 정의 된 기본 메소드 본문이있는 인터페이스 인 " Interface Defender Methods "라는 것이 있습니다. 방어자 메서드를 사용하는 여러 인터페이스를 구현하면 두 인터페이스 개체의 동작을 효과적으로 확장 할 수 있습니다.
또한 Groovy에서는 @Delegate 어노테이션을 사용하여 둘 이상의 클래스의 동작을 확장 할 수 있습니다 (이러한 클래스에 동일한 이름의 메소드가 포함 된 경우주의 사항). 이 코드는이를 증명합니다.
class Photo {
int width
int height
}
class Selection {
@Delegate Photo photo
String title
String caption
}
def photo = new Photo(width: 640, height: 480)
def selection = new Selection(title: "Groovy", caption: "Groovy", photo: photo)
assert selection.title == "Groovy"
assert selection.caption == "Groovy"
assert selection.width == 640
assert selection.height == 480
아니요, 한 클래스를 두 클래스로 확장 할 수 없습니다.
가능한 해결책은 다른 클래스에서 확장 하고 해당 클래스를 다른 클래스에서 다시 확장하는 것입니다.
Java는 다중 상속을 지원하지 않습니다. 그러나 인터페이스를 사용하여 문제를 해결할 수 있습니다.
쉬운 솔루션을위한 인터페이스를 생성하는 것입니다 AbstractBillingActivity
그리고 PreferenceActivity
그들 모두를 구현합니다.
당신이 요구하는 것은 다중 상속이며 여러 가지 이유로 매우 문제가 있습니다. 특히 Java에서는 다중 상속을 피했습니다. 대신 다중 인터페이스 구현을 지원하도록 선택했으며 이는 적절한 해결 방법입니다.
Java는 다중 상속을 지원하지 않으므로 두 개의 다른 클래스에서 동시에 클래스를 확장 할 수 없습니다.
대신 단일 클래스를 사용하여 확장하고 interfaces
추가 기능을 포함 하는 데 사용하십시오 .
다단계 계층 구조에 익숙하십니까?
하위 클래스를 다른 클래스의 수퍼 클래스로 사용할 수 있습니다.
이것을 시도 할 수 있습니다.
public class PreferenceActivity extends AbstractBillingActivity {}
그때
public class Preferences extends PreferenceActivity {}
In this case, Preferences class inherits both PreferencesActivity and AbstractBillingActivity as well.
I can think of a workaround that can help if the classes you want to extend include only methods.
Write these classes as interfaces. In Java, you can implements any number of interfaces, and implement the methods as default methods in the interfaces.
https://www.geeksforgeeks.org/default-methods-java/
Also, instead of inner classes, you can use your 2 or more classes as fields.
For example:
Class Man{
private Phone ownPhone;
private DeviceInfo info;
//sets; gets
}
Class Phone{
private String phoneType;
private Long phoneNumber;
//sets; gets
}
Class DeviceInfo{
String phoneModel;
String cellPhoneOs;
String osVersion;
String phoneRam;
//sets; gets
}
So, here you have a man who can have some Phone with its number and type, also you have DeviceInfo for that Phone.
Also, it's possible is better to use DeviceInfo as a field into Phone class, like
class Phone {
DeviceInfo info;
String phoneNumber;
Stryng phoneType;
//sets; gets
}
If you are interested in using methods from multiple classes, the best way to approach to it is to use Composition instead of Inheritence
In Groovy, you can use trait instead of class. As they act similar to abstract classes (in the way that you can specify abstract methods, but you can still implement others), you can do something like:
trait EmployeeTrait {
int getId() {
return 1000 //Default value
}
abstract String getName() //Required
}
trait CustomerTrait {
String getCompany() {
return "Internal" // Default value
}
abstract String getAddress()
}
class InternalCustomer implements EmployeeTrait, CustomerTrait {
String getName() { ... }
String getAddress() { ... }
}
def internalCustomer = new InternalCustomer()
println internalCustomer.id // 1000
println internalCustomer.company //Internal
Just to point out, its not exactly the same as extending two classes, but in some cases (like the above example), it can solve the situation. I strongly suggest to analyze your design before jumping into using traits, usually they are not required and you won't be able to nicely implement inheritance (for example, you can't use protected methods in traits). Follow the accepted answer's recommendation if possible.
참고URL : https://stackoverflow.com/questions/6587621/can-one-class-extend-two-classes
'Program Tip' 카테고리의 다른 글
Bash에서 연산자 "="와 "=="의 차이점은 무엇입니까? (0) | 2020.12.04 |
---|---|
URI 문자열이 유효한지 확인하는 방법 (0) | 2020.12.04 |
Twitter 부트 스트랩 탭 및 자바 스크립트 이벤트 (0) | 2020.12.04 |
JavaScript에서 입력 텍스트 값을 얻는 방법 (0) | 2020.12.04 |
servletcontext.getRealPath ( "/")는 무엇을 의미하며 언제 사용해야합니까? (0) | 2020.12.04 |