Menu
  • HOME
  • TAGS

Superclass method obtain subclass variable

java,subclass,superclass

Remove private int health = 30; which declares a new variable whose name hides the variable in the super class. And initialize in the constructor(s) public SubClass2() { super(); health = 30; } ...

Assign super to variable in AS3

actionscript-3,oop,inheritance,superclass

You are thinking of "this" and "super" as 2 different instances, 2 different things but they in fact point to the same object (obviously) so at the end it's always "this". Using super is just a special keyword that allows the instance to point to the overrided definitions up the...

Java getClass and super classes

java,superclass

Check the following code snippet which answers your question. Object O can hold any object. o.getClass() will return the run time class of the object public class Main { void method(Object o) { System.out.println(this.getClass() == o.getClass()); } public static void main(String[] args) { new Main().method(new Object()); // false new Main().method(new...

Why can't I add extra argument validation in the subclass constructor?

java,validation,constructor,abstract,superclass

As kocko notes, the super statement must be the first statement in your constructor. However, if you really, really don't want to get as far as the superconstructor before validating (e.g. because it will blow up with a less-helpful error), you can validate while evaluating the arguments to the superconstructor:...

Inheritance missing attribute

python,inheritance,superclass,super

You prefixed all your attribute names with two underscores. This triggers a name mangling mechanism that adds the class name to the attribute name, so child classes cannot override them. This is by design and is meant to avoid accidental overrides (kind of like a "private final" in Java) So...

Java generics: collection of super of super of some type

java,generics,superclass,super

Like so Collection<? extends Type<? super C>> superSuperTypes = mySuperType.getSuperTypes(); ...

Should I be using Super Classes?

java,superclass,super

If I'm understanding what you're saying, I think you're confusing the Is-a and Has-a relationships. A Term Has-a Course(s) A Course Has-a Assignment(s) This means that Course does not extend Term, but that Course and Term are independent classes. However, it may be that a Term Is-a ArrayList which Has-a...

What is the class of keywords like def, alias, and begin in Ruby, if any?

ruby,class,inheritance,keyword,superclass

They're keywords, not classes. If anything, they would be methods in Kernel, as opposed to classes with superclass BasicObject, but they're just keywords, and as such have neither class nor superclass. They're a special case and treated specially by the interpreter. Note that not everything that looks like a keyword...

Passing SuperClass constructor parameters to a SubClass?

inheritance,polymorphism,subclass,superclass

In your Account class you have specified a constructor that takes multiple arguments: firstName, lastName, accountNumber etc.. In the constructor of the subclass you have to invoke the constructor of the super class -> super() A little example: class Person { public String name; /*constructor*/ public Person(String name) { this.name...

Is it possible to have a class have more than one superclass?

java,swing,inheritance,subclass,superclass

When Sun was designing Java, it omitted multiple inheritance - or more precisely multiple implementation inheritance - on purpose. Yet multiple inheritance can be useful, particularly when the potential ancestors of a class have orthogonal concerns. This article presents a utility class that not only allows multiple inheritance to be...

Put different subclasses from the same base class into a list C#

c#,.net,subclass,superclass

That's because the interactionRequirements collection is of type InteractionRequirement not of the derived type (ObjectInteraction, CharacterIteraction or AssetInteraction). Therefore, you'll need a cast. string oName = ((ObjectInteraction)interactionRequirement[0]).ObjectName; You can also use as and check if the cast was successful. var objectInteraction = interactionRequirement[0] as ObjectInteraction; if (objectInteraction != null) {...

Accessing a method in a super super class

scala,superclass,super

This is not possible. The reason for that is, that it would violate encapsulation. See why is super.super not allowed in java and similar question for scala...

How do you call a subclass method from a superclass in Java?

java,inheritance,subclass,superclass

The answer for my specific JavaFX subclassing question is over here Subclassing a JavaFX Application. For general subclassing the answers here are quite adequate.

Can't reach fields from super class with object

java,oop,object,iteration,superclass

I don't know what the type of Ferry is, but perhaps Ferry.iterator() should return an Iterator<Vehicle> instead of Iterator<Object>. Then it.next() would return a reference to a Vehicle, which would allow you to access all the public members of Vehicle. Iterator<Vehicle> it = Ferry.iterator(); while(it.hasNext()){ Vehicle i = it.next(); System.out.println(i.color);...

When using the 'Class' datatype, how can I specify the type so I only accept subclass of a specific class?

actionscript-3,class,actionscript,superclass

If you are going to instantiate it anyway, why not accept an object instead which allows you to type it to :SuperClass? careless(SomeClass); //vs. careless(new SomeClass); Not too much of a problem there as far as your code goes. There are a few differences though: The object has to be...

Set/Get Methods for Private Fields in Super/Sub classes

java,subclass,private,superclass

You can create getter and setter methods in the superclass like: public GeometricFigure(int length, int width) { this.length = length; this.width = width; } public Rectangle(int length, int width) { super(length, width); } Your 2 constructors could look like this....

How can I access the members of a subclass from a superclass with a different constructor?

c++,inheritance,constructor,subclass,superclass

This map: typedef map<string, Object> obj_map; only stores Object objects. When you try to put an Image in, it is sliced down and you lose everything in the Image that was not actually part of Object. The behaviour that you seem to be looking for is called polymorphism. To activate...

How to build object hierarchy such that all nouns are words but not all words are nouns

arrays,class,swift,tableview,superclass

If nouns, verbs, etc are in fact types of words then that must be captured in the type hierarchy. As soon as you wrote class Noun and then class Verb you needed to stop and define the superclass. class Word {} class Noun : Word { /* ... */ }...

Purpose of implementing some subclasses and not others?

java,inheritance,superclass

If the sub-class doesn't explicitly contain an implementation then it will inherit the one from its' parent; note that means the other sub-classes (that do implement it explicitly) are overriding the implementation from the parent (this is known as Polymorphism). Similarly, every sub-class will inherit the interfaces that its' super-class...

Java: using setter of a subclass when creating an object of type Superclass

java,subclass,getter-setter,superclass

Cast p1 to Man: ((Man) p1).setAge(13); ...

Ontologies - Do superclasses get instances of their subclasses?

superclass,ontology,topbraid-composer

Actually this is the definition of superclass/subclass --- that all instances of a subclass are instances of a superclass. Don't know why the sparql query is not working. It's only going to work if the engine is inferencing, though, I think....

java how to get superclass reference in subclass

java,subclass,superclass

The reference to the current object is implicitly a reference to a superclass as well (as it extends it). So you should be able to do Generic g = new Generic(this); ...

Different Types of Subclass Objects with One Superclass [closed]

java,subclass,superclass

My Java is very rusty, so consider any code here to be pseudo-code just to demonstrate the concepts... You're not modeling the objects in code correctly. The code should match the real-world concepts being modeled. So let's consider those real-world concepts. What is a GeoFig? What does one look like?...

Inheritance :hidden variable of superclass in subclass

java,class,inheritance,subclass,superclass

You can access to it, using super: System.out.println(super.j); but you can use super inside the class A, so you can do something like this: public class A extends B { int j = 10; public void print() { System.out.println(super.j); } public static void main(String[] args) { A obj = new...

Java Polymorphism with ArrayLists

java,arraylist,polymorphism,subclass,superclass

switch (platform) { case 0: p.add(new GreenPlatform(x, y)); break; case 1: p.add(new RedPlatform(x, y)); break; case 2: p.add(new BluePlatform(x, y)); break; case 3: p.add(new MagentaPlatform(x, y)); break; case 4: p.add(new GrayPlatform(x, y)); } ...

Difficulty understanding RubyMonk exercise called “Whodunnit” involving superclasses

ruby,while-loop,superclass

is this creating a variable called 'superclass' to use in the rest of the 'while not loop', and then testing it as != nil, at the same time? Yes. The (blahblah).nil? is the loop condition, while the value of superclass is used within each iteration. while not (superclass =...

Subclasses and inheritance

android,inheritance,subclass,superclass

Best example could be the class all Android developers know : Activity. The doc clearly says that Activity extends ContextThemeWrapper which extends ContextWrapper which extends Context which extends Object. Object class has ".toString()" method. So, try to print in your console any object you instantiate (like your main Activity) to...

MATLAB: Set inherited properties to read-only

matlab,oop,inheritance,superclass

This seems like a case where you should prefer composition over inheritance. This idea is mentioned in one of the comments (@Dev-iL), where it's described as "not very OOP". I disagree - although inheritance is the right design in many cases, composition is often preferable. (See here and here for...

Python: case where x==y and x.__eq__y() return different things. Why?

python,object,inheritance,superclass

The NotImplemented value you're seeing returned from your inherited __eq__ method is a special builtin value used as a sentinel in Python. It can be returned by __magic__ methods that implement mathematical or comparison operators to indicate that the class does not support the operator that was attempted (with the...

How to cast subclass object to superclass object

java,inheritance,casting,subclass,superclass

A superclass cannot know subclasses methods. Think about it this way: You have a superclass Pet You have two subclasses of Pet, namely: Cat, Dog Both subclasses would share equal traits, such as speak The Pet superclass is aware of these, as all Pets can speak (even if it doesn't...

Is there any way to override methods in netbeans automatically?

java,netbeans,auto,superclass,overriding

Thanks to NetBeans, it can be done easily. Imagine this is your project structure: refactordemo |-- Parent.java |-- Child.java and this is the Sample code: Parent.java package refactordemo; public class Parent { public static void main(String[] args) { } public String method1() { return null; } } Child.java package refactordemo;...

Timer doesn't feel like overriding

java,timer,override,superclass

Well, indeed the @Override is negligible in this case. Yet, the codes for moving the label is of great importance. You should base it on this: In the action listener of the timer do something like this: x = x - 1; And then Label.setLocation(x,y); That should do the trick!...

AS3: Calling superclass method instead of subclass instance's override?

actionscript-3,inheritance,override,subclass,superclass

Short answer: Kind of, but it's not fun Long answer: I originally thought that it would be possible using the Function object and either apply() or call(), but the even though the docs (http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Function.html#apply()) say that you can pass another object, it doesn't work, it's always bounds to the declared...

Java superclass catch and subclass catch

java,exception,try-catch,subclass,superclass

The super class itself has no knowledge of its sub-classes, but the jvm has that knowledge, and jvm is doing the work for exception handling, polymorphism etc.

Getting clone of superclass

swift,clone,subclass,superclass

You mean subclass. Box is the superclass, which is what you're returning. This is very similar to the following: Protocol func returning Self Swift protocol and return types on global functions It's not exactly the same question, though, since you're dealing with classes rather than protocols, so we can go...

How to force call superclass implementation Object.toString() rather than subclass overriding implementation on an object in Java

java,override,superclass,subclassing

You need to use System.identityHashCode() to get the actual (original) hash code. Try this code: public static void main(String[] args) { String test = "StackOverflow"; Object testobj1 = (Object) test; System.out.println(testobj1.toString()); // prints "StackOverflow" System.out.println(testobj1.getClass().getName() + '@' + Integer.toHexString(System.identityHashCode(testobj1))); System.out.println(test.getClass().getName() + '@' + Integer.toHexString(System.identityHashCode(test))); Object testobj2 = new Object();...

ISA swizzling and calls to `super`

objective-c,superclass,objective-c-runtime,swizzling,isa-swizzling

The difference is minor, but important. The compiler is issuing a function call, not to objc_msgSendSuper, but to objc_msgSendSuper2. What's the difference, you may ask? It's minor, but important. From apple's open source: /******************************************************************** * * id objc_msgSendSuper(struct objc_super *super, SEL _cmd,...); * * struct objc_super { * id receiver;...

Call method from another method in abstract class with same name in real class

java,class,abstract-class,superclass

[...] but this.delete(id, true) call delete in FileGroup instead of calling delete in Controller. Yes, all methods are virtual in Java, and there's no way to avoid that. You can however work around this by creating a (non overridden) helper method in Controller as follows: public abstract class Controller...

Android: where in code super class must be calling

java,android,superclass

This entirely depends on whether you want your code to be run before or after the super implementation. There's no right or wrong. See these two examples: // prepend instructions to onPause @Override protected void onPause() { Log.debug("About to pause application..."); super.onPause(); } vs // append instructions to onPause @Override...

How to refer to parent class of base class from sub-sub-base-class static method without specifying base class name

php,subclass,static-methods,superclass,base-class

Store the parent class name inside a variable and use that variable to call the static method. Like this: $parentClassName = get_parent_class(get_parent_class()); echo $parentClassName::helloStatic(); ...

Unexpected output of “this.getClass().getSuperclass()”

java,inheritance,superclass

Simple answer: Because this is the superclass. public class TestClassOne { public TestClassOne() { System.out.println("Parent class of TestClassOne is :" + this.getClass().getSuperclass()); } } This class extends java.lang.Object (even if it is not explicitly named). So this references to an object of the class TestClassOne and the superclass is java.lang.Object....

Difference between two types of a super class instantiation in Java [duplicate]

java,object,java-ee,instantiation,superclass

The difference is for example if you have any information about document only in the document class, like, say, price. By doing Book book = new Book(); you won't be able to get the price of the book, so doing Document book = new Book(); will give you additional information...

Swift: Declaring a constant in a subclass but still have a reference to it in the superclass?

ios,swift,constants,subclass,superclass

You could do: class Apple { let color: String init(color: String) { self.color = color } } class RedDelicious: Apple { init() { super.init(color: "Red") } } Or instead, you could use read-only computed properties: class Apple { var color: String { return "" } } class RedDelicious: Apple {...

implicit super constructor Person() is undefined. Must explicitly invoke another constructor?

java,class,constructor,superclass

If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object...

What is invoking the super class constructor here?

java,inheritance,constructor,superclass,super

When you have a class that extends some other class, eg Cougar extends Feline, there must be a call to the super class at the top of the constructor. When you don't write one, Java assumes you meant to call the default super class constructor. So your constructor: public Cougar(){...

Can a subclass also be a superclass?

java,oop,inheritance,subclass,superclass

Yes, that behavior is exactly what is expected when using inheritance in Java. Here's some quick reading that you may find usefull: http://www.homeandlearn.co.uk/java/java_inheritance.html Your JackRussel object will inherit all fields and methods from it's Animal and Dog super-classes that are: not declared private; are not overridden (in which case will...

Java : Super class array object assigned with sub class array object

java,arrays,object,subclass,superclass

You can't do this: Cclass[] child = new Cclass[10]; Pclass[] parent = child; parent[0]=new Pclass(); You should try doing this: Cclass[] child = new Cclass[10]; Pclass[] parent = child; parent[0]=new Cclass(); That's because you first assigned the Pclass array to the child reference that can only have Cclass objects then...

Opposite tag to @Override in Java

java,methods,override,superclass,annotate

No, there is no pre-defined Java annotation that is the inverse of @Override. Having said that, most IDE's should be able to identify if a method is overriding another. For instance Eclipse has this feature. If you look at your class in Outline view, you'll see a small triangle where...

How does method redirection takes place in super class and base class?

java,superclass,base-class

Polymorphism is enforced dynamically (at runtime) based on the actual type of the object that is calling the method. It relies on the ability to assign an object of a subclass to a reference of the superclass. Also, notice that when you have an instance method in a class and...

Creating an array of superclasses for a particular class

ruby,loops,superclass

unless isn't a loop. What you're looking for is until: class Object def superclasses array = [] klass = self.superclass until klass == nil array << klass klass = klass.superclass end array end end class Bar end class Foo < Bar end p Foo.superclasses # Prints "[Bar, Object, BasicObject]" Furthermore,...

Should you use the superclass constructor to set variables?

java,inheritance,constructor,superclass

It is a standard practice to use the superclass constructor. It allows code reuse, when some validations on the variables might have been done in the superclass constructor. As an example, check this code from Apache Commons Collection. When used, super(..) must be the first statement within the child class...

Avoid repeating named argument defaults when calling superclass initializer in Ruby (2.1+)

ruby,superclass,named-parameters

In Ruby 2.0+, you can use the double splat operator. def initialize(bar: 456, **args) super(**args) @bar = bar end An example: [1] pry(main)> class Parent [1] pry(main)* def initialize(a: 456) [1] pry(main)* @a = a [1] pry(main)* end [1] pry(main)* end => :initialize [2] pry(main)> class Child < Parent [2]...

Output is “NaN”

java,class,superclass

save your milesPerGallon variable at constructor: public Car(double milesPerGallon) { this.milesPerGallon = milesPerGallon; gas = 0.0; } ...

My Subclass is passing values from its super class

java,inheritance,parameters,superclass

The p1 and p2 Point fields should be protected in the Segment class (not private because then your sub-class cannot access them). Thus you should remove the ones from HorizontalSegment because they add two new instances of Point with the same name as instances from the Segment (but they do...

Variable is null at super call

java,nullpointerexception,null,superclass,super

When you call new TestNull(); you're calling the constructor of the class TestNull, which it calls the super() constructor: it contains a call to the method implemented in TestNull, where you print the String field, at this time the fields of the sub-class TestNull are not yet initialized, i.e. are...

Fill a hashmap in superclass from subclass constructor in Java

java,javafx,subclass,abstract,superclass

What i understood is you have an Abstract class View, this class contains a static HashMap viewMap. This abstract class has some subclasses and each time a subclass is instantiated, you want that subclass get added to the viewMap object of super class. If i am right then the constructor...

Compare Object superclass package with Object package

java,inheritance,package,superclass

You're calling c.getClass().getPackage() when you should be calling c.getPackage(). c is already the superclass - it's a Class, so calling getClass() on it will just give you Class.class, which isn't what you want. I would try to be more consistent about it, like this: Class objectClass = o.getClass(); Class superClass...

Getting all superclasses in python 3

python-3.x,inheritance,superclass

Use the mro method: >>> class A(object): pass >>> class B(object): pass >>> class C(A, B): pass >>> C.mro() [<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <type 'object'>] ...

How to call subclass methods when subclass objects are stored in superclass array?

java,arrays,inheritance,subclass,superclass

You could initialize your objects before storing them in the array: Ship ships = new Ship(); ships.setShipName("Boom"); ships.setYearBuilt("1900"); CargoShip cargoShips = new CargoShip(); cargoShips.setShipName("Bang"); cargoShips.setCargoCapaicty(200); CruiseShip cruiseShips = new CruiseShip(); cruiseShips.setShipName("Bam"); cruiseShips.setMaxPassengers(500); Ship[] allShips = {ships, cargoShips, cruiseShips}; ...

Super class method using subclass method

java,override,subclass,superclass,super

When you have an instance of the subclass, you don't also have a separate instance of the super class. So when the super classes method calls calculateTotal() it calls the lowest (down the subclass chain) method defined for that signature. Sounds like you might want a calculateSubTotal() method that is...

libclang: get interface cursor from implementation cursor

objective-c,cursor,implementation,superclass,libclang

Calling clang_getCanonicalCursor() on the cursor for the @implementation declaration will return the cursor for the @interface declaration. Visiting the children of this cursor will provide access to its superclass reference. You can also use clang_getOverriddenCursors() on the cursor for the method to determine if it is overriding another from a...

Check if two classes have the same superclass [duplicate]

java,superclass,instanceof

Try Generic Superclass: private static boolean sameSuperclass(Class<?> leftClass, Class<?> rightClass) { if(rightClass.getGenericSuperclass().equals(leftClass.getGenericSuperclass())) return true; return false; } public static void main(String[] args) { System.out.println(sameSuperclass(Integer.class,Float.class)); //true System.out.println(sameSuperclass(TreeMap.class,ArrayList.class)); //false } ...

Relationship between LinearModel & GeneralizedLinearMixedModel classes

matlab,oop,time-series,linear-regression,superclass

To determine this, you can use the superclasses function: superclasses('LinearModel') superclasses('GeneralizedLinearMixedModel') This will return the names of the visible superclasses for each case. As you'll see, both inherit from the abstract superclass classreg.regr.ParametricRegression. You can also view the actual classdef files and look at the inheritances. In your Command Window,...

Java subclass constructor inherited member

java,constructor,subclass,superclass

TL;DR Problem is that implicitValue from SubClass is used by superclass implicit SuperClass constructor (super()) via implicitValue() method, before subClassValue = 20; will be executed in SubClass constructor, so it returns default value of subClassValue which for int field is 0. Does the SubClass constructor make use of the SuperClass...

cast on object of type superclass returns object of type subclass in java

java,binding,casting,subclass,superclass

This is two questions for the price of one. (1) Why do we get the implementation from class B, and (2) why do we get the version of the method with the parameter of type A. For question (1), the thing to remember is that the class of an object...

C++ inheritance, sending a pointer to base class

c++,pointers,inheritance,constructor,superclass

You just have to use the parameters as they originally are: ninjaCreep::ninjaCreep(Ogre::SceneManager& sceneManager, int x, int y, int z, std::string id) : Creep(sceneManager, x, y ,z, id) //line 4 no "*" { //ctor } sceneManager is not a pointer: it's a reference to an object of type SceneManger. It is...

Using “super” keyword or using a superclass instance when calling superclass methods locally in a method from subclass?

java,inheritance,instance,subclass,superclass

super.methodA(); Superclass superclass = new Superclass(); superclass.methodA(); These two calls of methodA work on different instances, so they are completely different. super.methodA() executes methodA on the current instance. superclass.methodA() executes methodA on a new instance of Superclass which is not related to the current instance. You would almost always...

Why HashMap with generic declaration “ does not accept value ”new Object()" in the put method?

java,generics,hashmap,wildcard,superclass

The type ? super ArrayList means an unknown type, which has a lower bound of ArrayList. For example, it could be Object, but might be AbstractList or ArrayList. The only thing the compiler can know for sure is that the type of the value, although unknown, is guaranteed to be...