Extending from two classes
You can only Extend a single class. And implement Interfaces from many sources.
Extending multiple classes is not available. The only solution I can think of is not inheriting either class but instead having an internal variable of each class and doing more of a proxy by redirecting the requests to your object to the object that you want them to go to.
public class CustomActivity extends Activity {
private AnotherClass mClass;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mClass = new AnotherClass(this);
}
//Implement each method you want to use.
public String getInfoFromOtherClass()
{
return mClass.getInfoFromOtherClass();
}
}
this is the best solution I have come up with.
You can get the functionality from both classes and Still only actually be of one class type.
The drawback is that you cannot fit into the Mold of the Internal class using a cast.
How can I extend multiple classes in typescript?
Yes, depending on the requirements there are several ways to do this. Given the classes A
and B
:
class A {
constructor(public i: number){}
foo() {
return 123;
}
}
class B {
constructor(public name: string){}
bar() {
return "Hello from B!";
}
}
you can do any of the following and have it just work (for some value of just-work):
Inherit one class, implement the other as an interface (in TypeScript any class may be treated as an interface):
class Cv1 extends B implements A { /* implement A-as-interface here */ }
Create a type alias for
A & B
and implement the type alias (e. g. treat both classes as interfaces):type AandB = A & B;
class Cv2 implements AandB {
constructor(public i: number, public name: string) {}
foo(...args: []) {
return A.prototype.foo.apply(this, args);
}
bar() {
return "Cv2 says GOODBYE!";
}
}Mix both classes together and inherit from the mixed class:
// Exercise for the reader: do it without any
function mixin(a: any, b: any): any {
// Choice: Should isA apply to either mixin? Should it apply to neither?
const aNotB = Object.defineProperties(Object.create(a.prototype), Object.getOwnPropertyDescriptors(b.prototype));
const shadowClass: any = function shadowClass(){}
shadowClass.prototype = aNotB;
class mixinImpl extends shadowClass {}
return mixinImpl;
}
class Cv3 extends mixin(A, B) { }
Caveat Emptor
There are limitations with this technique. For example, if B
has a prototype chain of its own (e. g. B extends BPrime
and BPrime extends BPrimordial
, etc.) then none of the methods and properties of BPrime
and BPrimordial
will be copied over (you can walk the prototype chain yourself at class construction time to work around this if that's what you want to do). Also, instanceof
will not work with any of the implements
or .assign
techniques (e. g. anInstanceOfC instanceof B
will be false
using any of the techniques above).
Typescript: How to extend two classes?
There is a little known feature in TypeScript that allows you to use Mixins to create re-usable small objects. You can compose these into larger objects using multiple inheritance (multiple inheritance is not allowed for classes, but it is allowed for mixins - which are like interfaces with an associated implenentation).
More information on TypeScript Mixins
I think you could use this technique to share common components between many classes in your game and to re-use many of these components from a single class in your game:
Here is a quick Mixins demo... first, the flavours that you want to mix:
class CanEat {
public eat() {
alert('Munch Munch.');
}
}
class CanSleep {
sleep() {
alert('Zzzzzzz.');
}
}
Then the magic method for Mixin creation (you only need this once somewhere in your program...)
function applyMixins(derivedCtor: any, baseCtors: any[]) {
baseCtors.forEach(baseCtor => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
if (name !== 'constructor') {
derivedCtor.prototype[name] = baseCtor.prototype[name];
}
});
});
}
And then you can create classes with multiple inheritance from mixin flavours:
class Being implements CanEat, CanSleep {
eat: () => void;
sleep: () => void;
}
applyMixins (Being, [CanEat, CanSleep]);
Note that there is no actual implementation in this class - just enough to make it pass the requirements of the "interfaces". But when we use this class - it all works.
var being = new Being();
// Zzzzzzz...
being.sleep();
Can one class extend two classes?
Java does not support multiple inheritance.
There are a few workarounds I can think of:
The first is aggregation: make a class that takes those two activities as fields.
The second is to use interfaces.
The third is to rethink your design: does it make sense for a Preferences
class to be both a PreferenceActivity
and an AbstractBillingActivity
?
How to extend two Classes on one activity
In Java, there is no way of extending from two classes
but you can get all the features of that class by creating a new object from that class and use it in your program.
You can also look at this link, it may help you
Update:
I used this method to use Google Maps APIs in my program without Extended class.
public class MapInfoFragment extends Fragment implements OnMapReadyCallback {
private static GoogleMap mMap;
public MapInfoFragment() {
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_travelling_info, container, false);
SupportMapFragment mMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.frmap);
lnl_map_fragment = rootView.findViewById(R.id.lnl_map_fragment);
mMapFragment.getMapAsync(this);
return rootView;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
googleMap.setMapType(1);
googleMap.getUiSettings().setMapToolbarEnabled(false);
googleMap.setIndoorEnabled(true);
googleMap.setBuildingsEnabled(true);
googleMap.setTrafficEnabled(false);
googleMap.getUiSettings().setZoomControlsEnabled(false);
googleMap.getUiSettings().setRotateGesturesEnabled(false);
googleMap.getUiSettings().setAllGesturesEnabled(false);
googleMap.getUiSettings().setTiltGesturesEnabled(false);
LatLngBounds.Builder builder = new LatLngBounds.Builder();
origin_marker_option.position(origin_ltln)
.title("Origin")
.icon(BitmapDescriptorFactory.fromBitmap(btm_origin))
.flat(false);
googleMap.addMarker(origin_marker_option);
if (ar_dest_lat_lon.size() > 0) {
dest_marker_option_1.position(ar_dest_lat_lon.get(0))
.title("Dest1")
.icon(BitmapDescriptorFactory.fromBitmap(btm_dest_1))
.flat(false);
googleMap.addMarker(dest_marker_option_1);
} else {
builder.include(new LatLng(origin_ltln.latitude - 0.003, origin_ltln.longitude - 0.003));
builder.include(new LatLng(origin_ltln.latitude + 0.003, origin_ltln.longitude + 0.003));
}
builder.include(origin_ltln);
for (LatLng dest_lat_lon : ar_dest_lat_lon)
builder.include(dest_lat_lon);
LatLngBounds bounds = builder.build();
int width = getResources().getDisplayMetrics().widthPixels;
int height = getResources().getDisplayMetrics().heightPixels / 3;
int padding = (int) (width * 0.12); // offset from edges of the map 12% of screen
int w = lnl_map_fragment.getWidth();
int h = lnl_map_fragment.getHeight();
int p = (int) (w * 0.12);
try {
mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, padding));
} catch (Exception e) {
e.printStackTrace();
}
initMapCameraPosition();
}
private void initMapCameraPosition() {
if (mMap == null) return;
}
}
- At the request of the respectable questioner, the code was placed
Multiple inheritance, 'need' to extend two classes
PHP doesn't support multiple inheritence. You can however rewrite your logic using traits to (sort of) simulate it.
class Field {
protected $name;
protected $value;
}
trait Dropdown {
protected $options = [];
// with functions like setOptions(), addOption(), removeOption() etc.
}
interface IntegrationPositions {
const LAYOUT_POSITION_LEFT = 'left';
const LAYOUT_POSITION_RIGHT = 'right';
}
trait Integration {
protected $layoutPosition = IntegrationPositions::LAYOUT_POSITION_LEFT;
}
class DropdownField extends Field {
use Dropdown;
}
class IntegrationField extends Field {
use Integration;
}
class DropdownIntegrationField extends Field {
use Integration,Dropdown;
}
Update: As @Adambean noted traits cannot have constants. I've therefore updated the example using an enum.
This feels strange to have to declare an enum that's meant to be internal to a trait but PHP does not seem to allow any other mechanism to achieve this as far as I know, I am open to any other ideas.
How can a class extend two classes in Java?
If java can only extend one class, and every class extends java.lang.Object, how can it extend another class?
When you say A extends B then it means that A extends B and B extends Object
. One class can inherit from another which can inherit from another and at the top of the chain is java.lang.Object
. Java doesn't support multiple inheritance , but supports multi-level inheritance.
how come every class doesn't have written "extends Object" ?
All classes extend Object
implicitly , so it will be redundant coding.
Extending two classes in another class?
Here the order of classes matters.
If you write
class Z(X,Y)
then my_print
method of class X
will be executed.
and if you write class Z(Y,X)
then my_print
method of class Y
will be executed.
note: there is built in print()
function in python, please rename it. And class names should be Pascal case.
Example: this will output 'x':
class X:
def my_print(self):
print('x')
class Y:
def my_print(self):
print('y')
class Z(X, Y):
pass
my_object = Z()
my_object.my_print()
and this will output 'y'
class X:
def my_print(self):
print('x')
class Y:
def my_print(self):
print('y')
class Z(Y, X):
pass
my_object = Z()
my_object.my_print()
Related Topics
Looking for a CSS Parser in Java
How Delete a Collection or Subcollection from Firestore
How to Kill a Linux Process in Java with Sigkill Process.Destroy() Does Sigterm
How to Avoid Java.Net.Bindexception: Address Already in Use
Animation on Transparent-Background Jframe Linux
Eclipse Swt Browser Crash (Linux 64Bit)
How to Add Multiple Jar Files in Classpath in Linux
Spring Security Does Not Allow CSS or Js Resources to Be Loaded
Hiding Strings in Obfuscated Code
How to Programmatically Set Drawableleft on Android Button
Noclassdeffounderror: Android.Support.V7.Internal.View.Menu.Menubuilder
Could Not Reserve Enough Space for Object Heap to Start Jvm
Java Getlocalhost() Unknownhostexception /Etc/Hosts File Differs Linux API
How to Solve the 'Lock Obtain Timed Out' When Using Solr Plainly
Webdriver for Firefox: Browser Starts W/ Empty Page, Hangs for 2 Min, Restarts, Then Test Runs. Why