CastOverrideAndAnonymusClasses
This commit is contained in:
8
castingandothers/src/main/java/com/example/Animal.java
Normal file
8
castingandothers/src/main/java/com/example/Animal.java
Normal file
@ -0,0 +1,8 @@
|
||||
package com.example;
|
||||
|
||||
class Animal{
|
||||
public String name;
|
||||
public void Animal(){
|
||||
this.name = "Something!!!";
|
||||
}
|
||||
}
|
12
castingandothers/src/main/java/com/example/Cat.java
Normal file
12
castingandothers/src/main/java/com/example/Cat.java
Normal file
@ -0,0 +1,12 @@
|
||||
package com.example;
|
||||
|
||||
public class Cat extends Animal {
|
||||
public String sound;
|
||||
public void Cat(){
|
||||
this.sound = "MEEEEOW";
|
||||
}
|
||||
public void makesound(){
|
||||
this.sound = "Something like MEEEEOW";
|
||||
System.err.println(sound);
|
||||
}
|
||||
}
|
41
castingandothers/src/main/java/com/example/Main.java
Normal file
41
castingandothers/src/main/java/com/example/Main.java
Normal file
@ -0,0 +1,41 @@
|
||||
package com.example;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
public class Main {
|
||||
public static void main(String[] args) {
|
||||
System.out.println("Hello world!");
|
||||
|
||||
double asd = 3.5423;
|
||||
int castedasd = (int) asd;
|
||||
System.out.println(castedasd);
|
||||
System.out.print("Gimme a letter and Ill tel you the ASCII code! ");
|
||||
Scanner read = new Scanner(System.in);
|
||||
char a = read.next().charAt(0);
|
||||
|
||||
//your code goes here
|
||||
System.out.println((int)a);
|
||||
|
||||
|
||||
// Upcasting
|
||||
// You can cast an instance of a subclass to its superclass.
|
||||
|
||||
// Consider the following example, assuming that Cat is a subclass of Animal.
|
||||
Animal C = new Cat();
|
||||
|
||||
Animal B = new Cat();
|
||||
System.out.println(((Cat)B).sound);
|
||||
|
||||
// Anonymous Classes
|
||||
// Anonymous classes are a way to extend the existing classes on the fly.
|
||||
|
||||
// For example, consider having a class Machine:
|
||||
Cat c = new Cat(){
|
||||
@Override public void makesound(){
|
||||
System.err.println("MOOOOOOOOOOOOOO");
|
||||
}
|
||||
};
|
||||
|
||||
c.makesound();
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user