Here is an example of polymorphism in pseudo-C # / Java:
class Animal { abstract string MakeNoise (); } class Cat : Animal { string MakeNoise () { return "Meow"; } } class Dog : Animal { string MakeNoise () { return "Bark"; } } Main () { Animal animal = Zoo.GetAnimal (); Console.WriteLine (animal.MakeNoise ()); }
The main function does not know the type of animal and depends on the specific behavior of the implementation of the MakeNoise () method.
class A { A(int number) { System.out.println("A's" + " "+ number); } } class B { A aObject = new A(1); B(int number) { System.out.println("B's" + " "+ number); } A aObject2 = new A(2); } public class myFirstProject { public static void main(String[] args) { B bObj = new B(5); } }
from: A 1 A 2 B 5
My rules: 1. Do not initialize the default values ββin the declaration (null, false, 0, 0.0 ...). 2. Assume initialization in the declaration if you do not have a constructor parameter that changes the value of the field. 3. If the field value changes due to the constructor parameter, place the initialization in the constructors. 4. Be consistent in your practice. (most important rule)
public class Dice { private int topFace = 1; private Random myRand = new Random(); public void Roll() {
or
public class Dice { private int topFace; private Random myRand; public Dice() { topFace = 1; myRand = new Random(); } public void Roll() {
source share