[Java] 简单的继承,方法重载与方法覆盖 →→→→→进入此内容的聊天室

来自 , 2019-10-28, 写在 Java, 查看 107 次.
URL http://www.code666.cn/view/90db9da4
  1. package com.jiarui;
  2.  
  3. public class Demo1 {
  4.  
  5.         public static void main(String[] args) {
  6.                
  7.                 Dog dog1= new Dog(2,"大黄");
  8.                 System.out.println(dog1.name+"的年龄为:"+dog1.getAge());
  9.                 dog1.Cry();
  10.                
  11.                 Cat cat1=new Cat(3,"小花");
  12.                 cat1.Cry();
  13.                 System.out.println(cat1.name+"的年龄为:"+cat1.getAge());
  14.                
  15.                 Abc abc= new Abc();
  16.                 System.out.println(abc.getNum(12,18));
  17.  
  18.         }
  19.  
  20. }
  21.  
  22. class Animal{
  23.     int age;
  24.         String name;
  25.        
  26.         public Animal(){
  27.                
  28.                 this.age=age;
  29.                 this.name=name;
  30.         }
  31.        
  32.         public void Cry(){
  33.                 System.out.println("动物的叫声是:不知道。");
  34.         }
  35. }
  36.  
  37. class Dog extends Animal{
  38.         //private int age;
  39.         //public String name;
  40.        
  41.         public Dog(int age,String name){
  42.                
  43.                 this.age=age;
  44.                 this.name=name;
  45.         }
  46.        
  47.         //方法的覆盖
  48.         public void Cry(){
  49.                
  50.                 System.out.println("狗的叫声是:汪汪");
  51.         }
  52.        
  53.         public int getAge(){
  54.                
  55.                 return this.age;
  56.         }
  57.        
  58. }
  59.  
  60. class Cat extends Animal{
  61.        
  62.         public Cat(int age,String name){
  63.                
  64.                 this.age=age;
  65.                 this.name=name;
  66.         }
  67.        
  68.         public void Cry(){
  69.                 System.out.println("猫的叫声是:喵喵!");
  70.         }
  71.        
  72.         public int getAge(){
  73.                
  74.                 return this.age;
  75.         }
  76. }
  77.  
  78. class Abc{
  79.        
  80.         public int getNum(int i,int j){
  81.                
  82.                 if (i>j) {
  83.                        
  84.                         return i;
  85.                 }else {
  86.                        
  87.                         return j;
  88.                 }
  89.         }
  90.         //方法重载:只是返回类型不一样,不能构成重载
  91.         public float getNum(float a,float b){
  92.                
  93.                 if (a>b) {
  94.                        
  95.                         return a;
  96.                        
  97.                 }else {
  98.                         return b;
  99.                 }
  100.         }
  101.        
  102.        
  103. }

回复 "简单的继承,方法重载与方法覆盖"

这儿你可以回复上面这条便签

captcha